How to apply multiple predicates to a java.util.Stream?

前端 未结 4 962
無奈伤痛
無奈伤痛 2020-11-27 12:10

How can I apply multiple predicates to a java.util.Stream\'s filter() method?

This is what I do now, but I don\'t really like it. I have a

4条回答
  •  温柔的废话
    2020-11-27 12:58

    If you have a Collection> filters you can always create a single predicate out of it using the process called reduction:

    Predicate pred=filters.stream().reduce(Predicate::and).orElse(x->true);
    

    or

    Predicate pred=filters.stream().reduce(Predicate::or).orElse(x->false);
    

    depending on how you want to combine the filters.

    If the fallback for an empty predicate collection specified in the orElse call fulfills the identity role (which x->true does for anding the predicates and x->false does for oring) you could also use reduce(x->true, Predicate::and) or reduce(x->false, Predicate::or) to get the filter but that’s slightly less efficient for very small collections as it would always combine the identity predicate with the collection’s predicate even if it contains only one predicate. In contrast, the variant reduce(accumulator).orElse(fallback) shown above will return the single predicate if the collection has size 1.


    Note how this pattern applies to similar problems as well: Having a Collection> you can create a single Consumer using

    Consumer c=consumers.stream().reduce(Consumer::andThen).orElse(x->{});
    

    Etc.

提交回复
热议问题