如何使用流api基于实体的两个不同列创建列表?

kuhbmx9i  于 2021-08-20  发布在  Java
关注(0)|答案(1)|浏览(252)

无法共享实际类,因此无法共享类似的场景。
说明:
单位名称:员工
列:名称、昵称等。。。
允许名称和昵称为null。
行动:
输入:列表<员工>
输出:列表(包含名称和昵称)
必须使用流类并生成列表。
必须检查两列上的空条件。如果不为空,则只有您必须将它们放入我们的最终列表中。
简而言之,我必须对员工列表中的“name”和“昵称”列执行空基筛选器,并创建一个字符串列表。

pgccezyw

pgccezyw1#

这是获得预期结果的方法之一

List<String> nameNickNameList = new ArrayList<String>();
        List<String> combinedList = new ArrayList<String>();
        // add all names to nameNickNameList 
        empList.stream().filter( e -> (nameNickNameList.add(e.getName()) )).collect(Collectors.toList()); 
        // add all nickNames to nameNickNameList 
        empList.stream().filter( e -> (nameNickNameList.add(e.getNickName()) )).collect(Collectors.toList());
        // filter out non null values and assign to combinedList 
        combinedList = nameNickNameList.stream().filter(s -> (s!=null) && !s.trim().isEmpty()).collect(Collectors.toList());

        for(String s : combinedList) {
            System.out.println(s);
        }

输入:emplist已

Employee e1 = new Employee("James","Jimmy", 20.5);
        Employee e2 = new Employee("Robert",null, 25.5);
        Employee e3 = new Employee("Kevin","Kev", 12.0);
        Employee e4 = new Employee("David","", 16.0);
        Employee e5 = new Employee("Alexander","Alex", 5.0);

输出

James
Robert
Kevin
David
Alexander
Jimmy
Kev
Alex

相关问题