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

前端 未结 4 970
無奈伤痛
無奈伤痛 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:44

    I've managed to solve such a problem, if a user wants to apply a list of predicates in one filter operation, a list which can be dynamic and not given, that should be reduced into one predicate - like this:

    public class TestPredicates {
        public static void main(String[] args) {
            List numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
            System.out.println(numbers.stream()
                    .filter(combineFilters(x -> x > 2, x -> x < 9, x -> x % 2 == 1))
                    .collect(Collectors.toList()));
        }
    
        public static  Predicate combineFilters(Predicate... predicates) {
    
            Predicate p = Stream.of(predicates).reduce(x -> true, Predicate::and);
            return p;
    
        }
    }
    

    Note that this will combine them with an "AND" logic operator. To combine with an "OR" the reduce line should be:

    Predicate p = Stream.of(predicates).reduce(x -> false, Predicate::or);
    

提交回复
热议问题