在Java 8中执行操作流内的操作

Kri*_*hna 7 java java-8 java-stream

我需要获得员工姓名包含"kumar"且年龄大于26的员工数.我使用Java 8流来迭代收集,我能够找到具有上述条件的员工数.

但是,与此同时,我需要打印员工的详细信息.

这是我使用Java 8流的代码:

public static void main(String[] args) {

    List<Employee> empList = new ArrayList<>();

    empList.add(new Employee("john kumar", 25));
    empList.add(new Employee("raja", 28));
    empList.add(new Employee("hari kumar", 30));

    long count = empList.stream().filter(e -> e.getName().contains("kumar"))
                          .filter(e -> e.getAge() > 26).count();
    System.out.println(count);
}
Run Code Online (Sandbox Code Playgroud)

传统方式:

public static void main(String[] args){
   List<Employee> empList = new ArrayList<>();

    empList.add(new Employee("john kumar", 25));
    empList.add(new Employee("raja", 28));
    empList.add(new Employee("hari kumar", 30));
    int count = 0;
    for (Employee employee : empList) {

        if(employee.getName().contains("kumar")){
            if(employee.getAge() > 26)
            {
                System.out.println("emp details :: " + employee.toString());
                count++;
            }
        }
    }
     System.out.println(count);
}
Run Code Online (Sandbox Code Playgroud)

无论我以传统方式打印什么,我都希望使用流来实现相同的目标.

使用流时,如何在每次迭代中打印消息?

Tun*_*aki 16

您可以使用该Stream.peek(action)方法记录有关流的每个对象的信息:

long count = empList.stream().filter(e -> e.getName().contains("kumar"))
                      .filter(e -> e.getAge() > 26)
                      .peek(System.out::println)
                      .count();
Run Code Online (Sandbox Code Playgroud)

peek方法允许在消耗流时对来自流的每个元素执行动作.该操作必须符合Consumer接口:获取t类型的单个参数T(stream元素的类型)并返回void.

  • 应该强调的是,`peek`只对*processed*项执行操作,因此如果你使用像`findFirst`那样的短路终端动作,它不一定会处理所有项目.此外,如果大小是可预测的,`count()`可以完全跳过处理,例如没有`filter`s.Java 9实现有这样的优化...... (2认同)