Stream anyMatch with List

nimo23 :

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());
Eran :

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());

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=474558&siteId=1