我有一个对象列表N,其中N是
N
|--- type (1,2,3)
|--- A (applicable if type 1)
|--- B (applicable if type 2)
|--- C (applicable if type 3)
|--- List<Integer> p
现在,我想要的结果是列表的过滤版本,如下所示:
create a list List<Integer> l
首先执行此操作:
if(type == 1) && (A > some_value):
Add all elements of p to l
select this N
稍后,一旦形成L:
if(type != 1)
if(l contains any element from p):
select this N
如何在一个步骤中使用streams实现这一点?
我可以先过滤并创建一个列表"l“,然后使用该列表进行过滤。
l = stream.filter(a -> a.type == 1 && a.A > some_value).collect(..)
然后,使用l进一步过滤。
但是有没有更好更精确的方法呢?
发布于 2019-05-30 07:49:54
if(键入== 1) && (A > some_value):将p的所有元素添加到l中选择这个N
我不知道"select this N“在这里是什么意思,因为您选择的是p
值,所以我忽略了该行。
Set<Integer> set = listOfN.stream()
.filter(n -> n.type == 1 && n.A > some_value)
.flatMap(n -> n.p.stream())
.collect(Collectors.toSet());
为了更好地执行下一步(contains()
),结果是从List
更改为Set
。
if(类型!= 1) if(l包含p中的任何元素):选择此N
List<N> result = listOfN.stream()
.filter(n -> n.type != 1 && n.p.stream().anyMatch(set::contains))
.collect(Collectors.toList());
https://stackoverflow.com/questions/56369807
复制相似问题