本文介绍了Java 8流API-根据条件进行过滤并收集对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Java 8中,根据某些过滤条件收集emp对象.
In java 8 , collect emp object based on some filter condition.
在主要班级
List<Emp> empList = Arrays.asList(
new Emp("aaa", language1),
new Emp("cc", language2),
new Emp("bb", language3),
new Emp("dd", language3)
);
empList.stream()
.flatMap(s->s.getLanguage().stream())
.filter(s->s.equals("java"))
.forEach(System.out::println); //Here just i am printing.
实际上我需要收集new List<EMP>
如何收集都具有语言"java"的emp对象.我该怎么办?
How to collect emp object who are all have language "java". How can I do?
推荐答案
如果最终要收集Emp
对象,则不应使用flatMap
,因为它会将每个元素都更改为其他元素,并且可能会相当很难将它们映射回去.
You should not use flatMap
if you want to collect Emp
objects in the end because it will change every element to something else and it can be quite hard to map them back.
您应该将所有逻辑放在filter
中:如果getLanguage
包含"java"
,请保留Emp
对象".
You should put all your logic in a filter
: "keep the Emp
object if getLanguage
contains "java"
".
empList.stream()
.filter(x->x.getLanguage().contains("java"))
.collect(Collectors.toList());
这篇关于Java 8流API-根据条件进行过滤并收集对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!