使用Java 8 Streams从列表中仅获取所需对象 [英] Getting only required objects from a list using Java 8 Streams

查看:115
本文介绍了使用Java 8 Streams从列表中仅获取所需对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑一个 Parent 类,其属性为 attrib1 attrib2 列出< Child> 具有相应getter和setter的子项。



是另一个具有五个属性 attrib1 - attrib5 及其相应的getter和setter的类。



现在我创建了一个列表< Parent> 父级。然后我想过滤掉列表< Parent> ,条件如下: - Child.Attrib1> 10 ;



所以我用Java 8流创建了以下查询。

  parent.stream()。filter(e  - > e.getChild()。stream()。anyMatch(c  - > c.getAttrib1()> 10)); 

但问题是我会在每个父母中获得所有孩子对象。在这里,我想只获得符合给定条件的 List< Child> 中的那些子对象。



应该如何我删除列表中不符合条件的所有子对象并获取新列表。

解决方案

如果你想要的话,你需要的是一个 Stream< Child> 接待所有孩子。下面的表达式可以解决这个问题:



parents.stream()。flatMap(e - > e.getChildren()。stream() ).filter(c - > c.getAttrib1()> 10)



这应该返回列表中所有父项的所有子项get属性值大于10的位置。



如果要通过删除条件失败的所有子元素来更新父列表,可以执行以下操作: / p>

parents.forEach(p - > p.getChildren()。removeIf(c - > c.getAttrib1()> 10)) ;



这不会创建新列表。相反,它会更新父母列表本身。


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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆