I have a list of "items" and each item has a property of item.posts (which is a list of post-instances).
I want to filter my "item"-list by two properties:
If "item.isBig" and if any post of a item is enabled, then collect the returned Stream
.
However, I don't know how to do the "anyMatch" with "i.getPosts#isEnabled".
items.stream()
.filter(Item::isBig)
.anyMatch(i.getPosts()->p.isEnabled) // this does not work
.collect(Collectors.toList());
anyMatch
is a terminal operation, so you can't use it in combination with collect
.
You can apply two filters:
List<Item> filtered =
items.stream()
.filter(Item::isBig)
.filter(i -> i.getPosts().stream().anyMatch(Post::isEnabled))
.collect(Collectors.toList());
or combine them into one filter:
List<Item> filtered =
items.stream()
.filter(i -> i.isBig() && i.getPosts().stream().anyMatch(Post::isEnabled))
.collect(Collectors.toList());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With