Java Reference
In-Depth Information
Chapter 1
Java 8: It's a Whole New Java
This topic is about lambdas (closures) in Java 8. More than that, though, it's about the new language that
Java has become. The revolution was not televised, and it was met with little fanfare, but it has happened.
It is possible for you to continue to write the same old Java code in our new Java 8 world, but unless you
get onboard with the revolution, you will increasingly discover code that is called “Java,” but which has
language, syntax, and customs that are foreign to you.
This topic is here to help you enter into this exciting new world. You should be eager to join this brave
new Java 8 world, because it will actually enable you to write code that is more succinct, more readable, and
more performant: it's rare that you get all three of these wins together, but lambdas in Java 8 bring all this to
the table.
To understand exactly where the new Java is coming from, let me go back into history. A long time
ago in an old version of Java, a member of my team wrote a piece of code that would clone a list, but
without including any of the null elements that may have been in the original list. That team member's
implementation looked something like Listing 1-1. The tech lead saw that code and was not impressed, and
so he rewrote it into Listing 1-2, which was longer, but both more readable and more efficient.
Listing 1-1. Original Implementation of cloneWithoutNulls(List)
public static <A> List<A> cloneWithoutNulls(final List<A> list) {
List<A> out = new ArrayList<A>(list);
while(out.remove(null)) {}
return out;
}
Listing 1-2. Refined Implementation of cloneWithoutNulls(List)
public static <A> List<A> cloneWithoutNulls(final List<A> list) {
List<A> out = new ArrayList<A>(list.size());
for(A elt : list) {
if(elt != null) out.add(e);
}
return out;
}
This is when I became responsible for that code. I reimplemented the method as something more
readable to my eyes. I did so by leveraging Apache's Commons-Collections library. This creates the
implementation given in Listing 1-3. The additional readability is because Commons-Collections has a way
 
Search WWH ::




Custom Search