Java Closures and Lambda.pdf

(1608 KB) Pobierz
in
d
un
8
fo
a
As
av
J
www.allitebooks.com
For your convenience Apress has placed some of the front
matter material after the index. Please use the Bookmarks
and Contents at a Glance links to access them.
www.allitebooks.com
Contents at a Glance
About the Author .....................................................................................................
xi
About the Technical Reviewer ...............................................................................
xiii
Acknowledgments ...................................................................................................xv
Introduction ...........................................................................................................xvii
Chapter 1: Java 8: It’s a Whole New Java .............................................................
1
Chapter 2: Understanding Lambdas in Java 8 .....................................................
11
Chapter 3: Lambda’s Domain: Collections, Maps, and Streams ..........................
33
Chapter 4: I/O with Lambdas ...............................................................................
51
Chapter 5: Data Access with Lambdas ................................................................
71
Chapter 6: Lambda Concurrency .........................................................................
95
Chapter 7: Lambdas and Legacy Code...............................................................
111
Chapter 8: Lambdas in Java Bytecode ..............................................................
139
Appendix A: A Tour of Paradigms ......................................................................
153
Index .....................................................................................................................
195
iii
www.allitebooks.com
Introduction
his book is the culmination of many brash years and hard lessons. he story starts all the way back when
I migrated from C++ into perl. he perl programming language was amazingly powerful compared to the
low-level manipulations and bookkeeping of C++. (he fact that it was “slow” never bothered me – I would
rather write powerful, efective slow code than weak, buggy fast code.) In the world of perl, there was the idea of
an “anonymous subroutine” that could be passed around and manipulated. You could also directly manipulate
the symbol table. he symbol table is the collection of function names available to the program. Between these
two things, I realized that I could code at a higher level: I could write subroutines that returned subroutines and
store those into the symbol table, efectively having my code write code at runtime. In perl, these subroutine
factories are called “template functions.” I proceeded to write some truly unreadable – but truly powerful – perl.
I shared this revelation with my friend and mentor, Brian Hurt. He was the grizzled veteran developer who
seemed to have seen it all. Brian told me that what I was doing was this thing called “functional programming,”
and encouraged me to look into proper functional languages, speciically OCaml, and its derivative, JoCaml.
I was immediately hooked. By 2008, I presented “Why Rubyists Should Learn OCaml” to the Ruby Users
Group of Minnesota (Ruby.MN).
1
here was a power in functional programming that was truly incredible
compared to the then-standard way of writing code. Moreover, my mathematical background played very
nicely with functional programming: the fact that state did not change meant that I could employ the same
kind of reasoning to my programs that I employed with mathematical equations. I presumed at the time that a
functional programming language would rise and fundamentally transform what it means to program, much
as Java ascended and made Object Oriented Programming ubiquitous. So far, this hasn’t happened.
he next chapter came with the rise of the Groovy programming language. Groovy’s MetaClass
functionality provided a way for me to perform the same tricks as in perl, but in a way that leveraged all that
existing Java code. his was having my cake and eating it, too. All that open source software that existed
for Java, and all that technical expertise that had been built up on the JVM could inally mix with these
“functional stunts.” It wasn’t functional programming – and I got in quite a bit of trouble on the Internet for
saying as much – but it was certainly borrowing some powerful tricks from functional programming. We get
into what was happening in chapter 1.
When Java 7 rolled out, it introduced the invokedynamic keyword (which we cover in chapter 8). he
keyword was touted as being support for dynamic languages, but I recognized it for what it was: JVM support
for those same functional stunts. here was no longer any technical reason why you could not perform the
same functional stunts in Java itself. he Java language’s syntax, however, simply could not keep up with its
underlying implementation. We had to wait until Java 8. With Java 8, we inally got lambdas into the Java
language itself, along with basic support for some of the most powerful functional stunts.
his is a truly exciting language change. I think it is as transformative to the Java language as the
introduction of object oriented programming in the irst place, and it shows that the functional stunts, which
were esoteric yet impressive back in perl, are truly primed to become industry standard practices. hat is
why this book is so critical: it is no exaggeration to say that learning the content in this book will help you
program throughout the remainder of your career. Sooner or later, you are going to have to learn to harness
the power of lambdas. Might as well start now.
1
http://www.youtube.com/watch?v=2T5syww4Nn4.
xvii
www.allitebooks.com
CHAPTER 1
Java 8: It’s a Whole New Java
This book 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 book 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>
List<A> out = new
for(A elt : list)
if(elt !=
}
return out;
}
cloneWithoutNulls(final List<A> list) {
ArrayList<A>(list.size());
{
null) out.add(e);
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
1
www.allitebooks.com
Zgłoś jeśli naruszono regulamin