Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stream anyMatch with List

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());
like image 251
nimo23 Avatar asked Sep 13 '17 11:09

nimo23


1 Answers

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());
like image 50
Eran Avatar answered Oct 14 '22 11:10

Eran