sakura :
I have a list of objects N, where N is
N
|--- type (1,2,3)
|--- A (applicable if type 1)
|--- B (applicable if type 2)
|--- C (applicable if type 3)
|--- List<Integer> p
Now, the result I want is filtered version of List such that:
create a list List<Integer> l
Do this first:
if(type == 1) && (A > some_value):
Add all elements of p to l
select this N
Later once L is formed:
if(type != 1)
if(l contains any element from p):
select this N
How to achieve this using streams in one step?
I can filter and create a list "l" first and then use that list to filter.
l = stream.filter(a -> a.type == 1 && a.A > some_value).collect(..)
Then, use l to filter further.
But is there a better and precise way?
Andreas :
if(type == 1) && (A > some_value): Add all elements of p to l select this N
Don't know what "select this N" means here, since you're selecting p
values, so I'm ignoring that line.
Set<Integer> set = listOfN.stream()
.filter(n -> n.type == 1 && n.A > some_value)
.flatMap(n -> n.p.stream())
.collect(Collectors.toSet());
For better performance of the next step (contains()
), the result was changes from List
to 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());