Java Reference
In-Depth Information
of saying, “Give me all of the collection's elements where some predicate is true.” 1 Because they had this
predicate infrastructure, you can express that idea succinctly. I thought that I had really made some progress
in clarifying and simplifying the code. Plus, if we ever needed to add another criterion to filter on, it's easy to
extend the Predicate to make that happen.
Listing 1-3. Apache Commons-Collections Implementation of cloneWithoutNulls(List)
public static <A> List<A> cloneWithoutNulls(final List<A> list) {
Collection<A> nonNulls = CollectionUtils.select(list, PredicateUtils.
notNullPredicate());
return new ArrayList<>(nonNulls);
}
Unfortunately, the time came when the new hot library, Google's Guava, replaced Apache
Commons-Collections on this project. Guava also contains a Predicate infrastructure, but it has an entirely
different package name, inheritance tree, and API than the Commons-Collections Predicate infrastructure.
Because of that, we had to change the method to the new code in Listing 1-4.
Listing 1-4. Google Guava Implementation of cloneWithoutNulls(List)
public static <A> List<A> cloneWithoutNulls(final List<A> list) {
Collection<A> nonNulls = Collections2.filter(list, Predicates.notNull());
return new ArrayList<>(nonNulls);
}
The problem is that the Predicate infrastructure was useful, but Java didn't have it in its core, and so
extensions to the standard library such as Guava and Apache Commons each ended up building their own
implementations. Of course, none of these implementations are compatible with the others. The alternative
JVM languages also started shipping their own (universally mutually incompatible) implementations. With
Java 8, we finally have a canonical implementation of that infrastructure and a lot more with it. The directly
converted Java 8 version of this code looks like Listing 1-5.
Listing 1-5. Java 8 Predicate Implementation of cloneWithoutNulls(List)
public static <A> List<A> cloneWithoutNulls(final List<A> list) {
List<A> toReturn = new ArrayList<>(list);
toReturn.removeIf(Predicate.isEqual(null));
return toReturn;
}
But these predicates are not the extent of what Java 8 introduces. There's a whole new syntax to
succinctly express this idea: see Listing 1-6. That right arrow? That's an example of the most exciting new
feature of Java 8: it's a lambda. But it goes even further. You will increasingly see Java code that looks like
Listing 1-7. In this example, we have an interface (Comparator) with static and instance methods, and some
real strangeness happening involving two colons. What is going on? That's the Java 8 revolution, and that's
what this topic is all about.
1 Unfortunately, they don't have the same capability with Lists specifically, so I had to do some work to get to the
right type.
 
Search WWH ::




Custom Search