使用 Java 8 Streams 从列表中仅获取所需的对象 [英] Getting only required objects from a list using Java 8 Streams
问题描述
考虑一个具有 attrib1
、attrib2
和 List
属性的 Parent
类及其对应的子级getter 和 setter.
Child
是另一个具有五个属性 attrib1
-attrib5
及其对应的 getter 和 setter 的类.
现在我创建了一个 List
父级.然后我想用以下条件过滤掉 List
:- Child.Attrib1 >10
;
所以我通过 Java 8 流创建了以下查询.
parent.stream().filter(e -> e.getChild().stream().anyMatch(c -> c.getAttrib1() > 10));
但问题是我会在每个 Parent
对象中获取所有孩子.在这里,我只想获取 List
中符合给定条件的那些子对象.
我应该如何删除List中不符合条件的所有子对象并获得新的List.
如果你想接收所有的孩子,你需要的是一个 Stream
.以下表达式可能会起作用:
parents.stream().flatMap(e -> e.getChildren().stream()).filter(c -> c.getAttrib1() > 10)
>
这应该返回列表中 get 属性值大于 10 的所有父级的所有子级.
如果您想通过删除所有不符合条件的子元素来更新父列表,您可以执行以下操作:
parents.forEach(p -> p.getChildren().removeIf(c -> c.getAttrib1() > 10));
这不会创建新列表.相反,它会更新 parents
列表本身.
Consider a Parent
class with the attributes attrib1
, attrib2
and List<Child>
child with its corresponding getters and setters.
The Child
is another class with five attributes attrib1
-attrib5
with its corresponding getters and setters.
Now I created a List<Parent>
parent. Then I want to filter out a List<Parent>
with following condition:- Child.Attrib1 > 10
;
So I created the following query by Java 8 streams.
parent.stream().filter(e -> e.getChild().stream().anyMatch(c -> c.getAttrib1() > 10));
But the problem is I will get all the child in each Parent
object. Here I want to get only those child object in List<Child>
that obeys the given condition.
How should I remove all the child objects in List that doesn't obeys the condition and get the new List.
What you need is a Stream<Child>
if you want to receive all children. The following expression might do the trick:
parents.stream().flatMap(e -> e.getChildren().stream()).filter(c -> c.getAttrib1() > 10)
This should return all children of all parents in the list where the get attribute value is greater than 10.
If you want to update the parents list by removing all child elements that fail a condition, you can do the following:
parents.forEach(p -> p.getChildren().removeIf(c -> c.getAttrib1() > 10));
This doesn't create a new list. Instead it updates the parents
list itself.
这篇关于使用 Java 8 Streams 从列表中仅获取所需的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!