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

时间:2015-08-20 13:31:54

标签: 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);
}

传统方式:

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);
}

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

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

2 个答案:

答案 0 :(得分:16)

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

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

peek方法允许在使用流时对流中的每个元素执行操作。该操作必须符合Consumer接口:采用类型t的单个参数T(流元素的类型)并返回void

答案 1 :(得分:2)

相当不清楚,你真正想要什么,但这可能会有所帮助:
Lambda(与您的Predicate一样)可以用两种方式书写:
没有这样的括号:e -> e.getAge() > 26

...filter(e -> {
              //do whatever you want to do with e here 

              return e -> e.getAge() > 26;
          })...