Showing posts with label Predicate. Show all posts
Showing posts with label Predicate. Show all posts

Friday, September 2, 2016

Default Methods on Functional Interfaces

By definition, all functional interfaces have a single abstract method. This doesn’t mean that they have only one method, though. Several of the common functional interfaces provide a number of helpful default methods.
Suppose that we have these two Predicates:

Predicate<String> egg = s -> s.contains("egg");
Predicate<String> brown = s -> s.contains("brown");

Now we want a Predicate for brown eggs and another for all other colors of eggs:

Predicate<String> brownEggs = egg.and(brown);
Predicate<String> otherEggs = egg.and(brown.negate());

Neat! Now we are reusing the logic in the original Predicates to build two new ones. It’s shorter and clearer what the relationship is between the Predicates.