Java 8 - Filter with BiPredicate

user2919910 picture user2919910 · Mar 15, 2016 · Viewed 11k times · Source

I have a Stream of Integer and I would like to find the two numbers whose sum is equals to another number. So I came up with the following solution:

BiPredicate<Integer, Integer> p = (price1, price2) -> price1.intValue() + price2.intValue() == moneyQty;
flavoursPrices.filter(p);

But the filter method does not receive a BiPredicate. Why not? What is an alternative for that?

Answer

Matt picture Matt · Dec 24, 2016

You can still work with Bipredicate. The argument that the filter-method needs is a Predicate, so here is an example of how to use this BiPredicate:

 BiPredicate<Integer, Integer> p = (price1, price2) -> price1.intValue() + price2.intValue() == moneyQty;

flavoursPrices.stream().filter(el->p.test(el.price1,el.price2));

In this example flavoursPrices must be a List.

The lambda that we are using:

el->p.test(el.price1,el.price2)

Is replacing the anonymous inner class declaration for creating a new Predicate out of the BiPredicate:

 Predicate<Integer> arg =new Predicate<Integer>() {
        @Override
        public boolean test(Element el) {
            return p.test(el.price1,el.price2);
        }
    };

So to filter the stream, we are creating a new Predicate for every element coming from the stream and than we use this Predicate as argument to use it's test-method. The big advantage of this is, that we don't have to create enormous amounts of Predicates in advance, but we can pass every element in the lambda function and get it's attributes.