在 Java 8 中的操作流内执行操作
Perform action inside stream of operation in Java 8
我需要获取员工姓名包含 "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);
}
无论我以传统方式打印什么,我都想使用流实现相同的效果。
如何在使用流时在每次迭代中打印一条消息?
不太清楚您真正想要什么,但这可能会有所帮助:
Lambdas(就像你的 Predicate
)可以用两种方式编写:
没有像这样的括号:e -> e.getAge() > 26
或
...filter(e -> {
//do whatever you want to do with e here
return e -> e.getAge() > 26;
})...
您可以使用 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
类型(流元素的类型)和 return void
.[= 的单个参数 t
19=]
我需要获取员工姓名包含 "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);
}
无论我以传统方式打印什么,我都想使用流实现相同的效果。
如何在使用流时在每次迭代中打印一条消息?
不太清楚您真正想要什么,但这可能会有所帮助:
Lambdas(就像你的 Predicate
)可以用两种方式编写:
没有像这样的括号:e -> e.getAge() > 26
或
...filter(e -> {
//do whatever you want to do with e here
return e -> e.getAge() > 26;
})...
您可以使用 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
类型(流元素的类型)和 return void
.[= 的单个参数 t
19=]