这是使用Java Streams的正确方式吗?

3

我一直在研究Java Streams。我有一个Employee对象,我正在根据年龄对对象进行分组,并需要将员工的姓名与之配对。这样做是否正确,或者我使用了太多循环?

employeeList.stream().collect(Collectors.groupingBy(person -> person.age))
    .forEach((age, person) -> {
      System.out.print("In the age " + age + " the following people are present ");
      person.forEach(name -> System.out.print(name.getFirstName() + ", "));
      System.out.println("");
    });
1个回答

8
我建议将数据收集与数据展示分开处理。
Map<Integer,String> namesByAge = 
    employeeList.stream()
                .collect(Collectors.groupingBy(Employee::getAge, 
                                               Collectors.mapping(Employee::getFirstName,
                                                                  Collectors.joining(","))));

现在您可以打印每个年龄组的名称:
namesByAge.forEach((age, names) ->
  System.out.println("In the age " + age + " the following people are present " + names));

希望我掌握了方法名称。根据您的代码,我假设Employee有一个返回intgetAge()方法和一个返回StringgetFirstName()方法。

或者 list.stream().collect(Collectors.groupingBy(Employee::getAge,Collectors.mapping(Employee::getFirstName,Collectors.toList()))) .entrySet().stream().forEach(e -> { System.out.println("在年龄 " + e.getKey() + " 的人有 " + e.getValue()); }); - Hadi J
5
使用.entrySet().stream().forEach(…)而不是仅使用.forEach(…)需要您处理Map.Entry方法getKey()getValue(),而不是仅通过名称引用键和值。因此,这更加复杂。 - Holger
6
这个解决方案与问题的原始代码有细微差别,因为它没有尾随逗号。但对于大多数情况来说,这是一个改进... - Holger
1
@Eran,我真的很喜欢将数据收集和展示分开。这是一种更清晰的方法。 - Vinnie

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接