Phase XI
Functional Java
You have been writing lambdas since Phase X without being told what they are.
This phase teaches almost no new ideas. An interface with one method is Phase VIII. An anonymous class is Phase VII. Generics are Phase IX. A lambda is those three things with the noise removed, and a stream is a loop you describe instead of writing. What is new is the shift: for the first time, behaviour travels through your program as an argument rather than being locked inside an object.
When you finish this phase you can
- Say why a method could not take another method, and what changed
- Recognise a functional interface and explain what makes it one
- Read and write a lambda without translating it back into a class in your head
- Build a comparator out of parts instead of writing a compare method
- Explain what a stream does before it is asked for an answer, and why
- Use Optional as a return type without turning it into a null check
- Say when a parallel stream is faster and when it is slower
- 11.1Lambdas and Functional InterfacesYou want to tell a method how to do a job. Java only lets you pass variables, so for twenty years you wrapped the job in a class. This is the phase where you stop.Lambda
- 11.2Method References and the Four ShapesJava ships forty functional interfaces and you need four of them. Learn those four, learn the two colons, and most functional code stops looking like a new language.Method referenceFunction, Predicate, Supplier, Consumer
- 11.3Streams, and When the Work HappensA stream is not a collection. It is a description of work that has not started yet, and knowing exactly when it starts explains almost everything surprising about them.Stream
- 11.4The Operations, and What collect Really DoesThirty methods split cleanly in two. Does it hand back a stream, or an answer. Once you sort them by that question, the list stops being a list to memorise.Collector
- 11.5Optional, and the Habit It Is Trying to BreakA method that might not find anything has to say so somehow. Returning null says it in a way the compiler cannot see, and that is the whole problem.Optional
- 11.6Parallel Streams and the Primitive OnesOne word splits your work across every core in the machine. The same word makes small jobs four times slower and can silently lose most of your data.Parallel stream