我有一个对象列表 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
现在,我想要的结果是 List 的过滤版本:
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
如何使用流一步实现这一目标?
我可以先过滤并创建一个列表“l”,然后使用该列表进行过滤。
l = stream.filter(a -> a.type == 1 && a.A > some_value).collect(..)
然后,使用 l 进一步过滤。
但是有没有更好、更精确的方法呢?
最佳答案
if(type == 1) && (A > some_value): Add all elements of p to l select this N
不知道“选择此 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(type != 1) if(l contains any element from p): select this N
List<N> result = listOfN.stream()
.filter(n -> n.type != 1 && n.p.stream().anyMatch(set::contains))
.collect(Collectors.toList());
关于Java 8 根据列表部分的条件过滤列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56369807/