[英]Perform action inside stream of operation in Java 8
I have a requirement to get the count of employees where employee name contains "kumar" and age is greater than 26. I am using Java 8 streams to iterate over the collection and I'm able to find employee count with above said condition. 我需要获得员工姓名包含“kumar”且年龄大于26的员工数量。我使用Java 8流来迭代收集,我能够找到具有上述条件的员工数量。
But, in the meantime, I need to print the employee details. 但是,与此同时,我需要打印员工的详细信息。
Here's my code using Java 8 streams: 这是我使用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);
}
Traditional way: 传统方式:
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);
}
Whatever I am printing in the traditional way, I want to achieve the same using streams also. 无论我以传统方式打印什么,我都希望使用流来实现相同的目标。
How do I print a message within each iteration when using streams? 使用流时,如何在每次迭代中打印消息?
You could use the Stream.peek(action)
method to log info about each object of your stream : 您可以使用
Stream.peek(action)
方法记录有关流的每个对象的信息:
long count = empList.stream().filter(e -> e.getName().contains("kumar"))
.filter(e -> e.getAge() > 26)
.peek(System.out::println)
.count();
The peek
method allows performing an action on each element from the stream as they are consumed. peek
方法允许在流消耗时对流中的每个元素执行操作。 The action must conform to the Consumer
interface: take a single parameter t
of type T
(type of the stream element) and return void
. 该操作必须符合
Consumer
接口:采用类型为T
的单个参数t
(stream元素的类型)并返回void
。
Rather unclear, what you actually want, but this might help: 相当不清楚,你真正想要什么,但这可能会有所帮助:
Lambdas (like your Predicate
) can be written in two ways: Lambdas(就像你的
Predicate
)可以用两种方式编写:
Without brackets like this: e -> e.getAge() > 26
or 没有这样的括号:
e -> e.getAge() > 26
或
...filter(e -> {
//do whatever you want to do with e here
return e -> e.getAge() > 26;
})...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.