#TodayILearned a #gotcha with #Predicate in #Java. You can learn, too!
 
Here's 1 way to write a Predicate:
 
static Predicate<String> isEmpty() {
    return p -> 0 == p.length();
}

And here's another way:
 
static Predicate<String> isEmpty = (p) -> {
    return 0 == p.length();
}
 
Erm. What's the difference?
 
Well. The first is a method that generates a function, and you call it like this:
 
boolean test = isEmpty().test("Hello!");
 
Or, from a stream in a method in a class named World:

.filter(World::isEmpty())
 
The second is a field with a pregenerated function, and you call it like this:
 
boolean test = isEmpty.test("Hello!");
 
Or, from a stream in a method in a class named World:

.filter(World.isEmpty)
 
Notice how the method-based Predicate still has to generate a function, and thus has to be called with parentheses.
 
The field-based predicate already generated its function by the time it gets called, and because it's a field, no parentheses are used for accessing it.
 
Why Predicates at all, rather than a simple boolean-returning method?
 
Beats the heck out of me. 
2

Keep in touch with Experts Exchange

Tech news and trends delivered to your inbox every month