【问题标题】:How to create list based on two different columns of an entity using Stream API?如何使用 Stream API 基于实体的两个不同列创建列表?
【发布时间】:2021-07-09 02:31:46
【问题描述】:

无法分享实际课程,所以分享一些类似的场景。

说明:

实体名称:员工

列:姓名、昵称等...

  • 名称和昵称允许为空。

行动:

  • 输入:列表

  • 输出:列表。 (包含姓名和昵称)

  • 必须使用流类并生成列表。

  • 必须检查两列的空条件。如果不为空,则只需将它们放入我们的最终列表中。

  • 简而言之,我必须对员工列表中的“名称”和“昵称”列执行空基本过滤器,并创建一个字符串列表。

【问题讨论】:

  • 你至少可以分享你对这个问题的尝试

标签: java java-8


【解决方案1】:

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

        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

【讨论】:

  • 首先感谢您的回答,但是我已经使用经典的for循环方法放置了一个解决方案。我也已经尝试过这种方式,但是它需要太多的代码行。我想使用 Stream API(如果可能)在单流中实现相同的功能。
猜你喜欢
  • 1970-01-01
  • 2021-09-18
  • 2021-09-17
  • 1970-01-01
  • 2022-10-24
  • 2019-11-10
  • 2022-11-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多