AnyMatch stream with a list

I have a list of "elements" and , each element has a property item.posts (this is a list of post instances).

I want to filter my "item" -list with two properties:

If "item.isBig" and if any item position is included, then pick up the return one Stream.

However, I do not know how to do "anyMatch" with "i.getPosts # isEnabled".

items.stream()
     .filter(Item::isBig)
     .anyMatch(i.getPosts()->p.isEnabled) // this does not work
     .collect(Collectors.toList());
+4
source share
1 answer

anyMatchis a terminal operation, so you cannot 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());
+7
source

Source: https://habr.com/ru/post/1685590/


All Articles