Functional Programming: Functions and Tuples
Explore Java 8 functional programming features focusing on the Function interface and Tuples. Understand how to use lambda expressions, method references, and immutable data structures for better concurrency and function composition. Learn to create and use Tuples to manage multiple values without extra class overhead.
Overview
Java 8 manages to add many features of the functional languages without significantly changing the Java language.
When lambda expressions, method-references, the Stream interface, and immutable data-structures are combined, Java enables a form of functional programming (FP).
For the purposes of this book, the three pillars of FP are as follows:
- Functions
- Immutability
- Concurrency
Functions
Java 8 manages to add many of the features of functional languages without significantly changing the Java language.
The Function interface (and related interfaces IntFunction, DoubleFunction, LongFunction, BiFunction, etc.) represents the compromise made by Java 8 in elevating functions to objects. This interface
allows functions to be passed as arguments, stored as variables, and returned by methods.
The Function interface has the following default methods:
andThen(Function): Returns a composed function that first applies this function to its input, and then applies the given function to the result.compose(Function): Similar toandThenbut in reversed order (first applies the given function to its input, and then this function).identity(): Returns a function that always