Sub topic 10
Combining Small Functions into Bigger Ones
You already know how to write small lambdas such as x -> x * 2 or s -> s.isEmpty(). Real programs often need bigger behavior, like "double a number, then add three" or "keep words that are not empty and are short." You could write one large lambda for each case. A cleaner way is to compose small ones. To compose is to join two pieces of behavior so they work as one.
Java makes this easy with default methods. A default method is a method that already has code inside an interface. Function, Predicate, and Comparator each come with default methods that build new lambdas from old ones.
Chaining Functions with andThen and compose
Function has two methods for joining functions:
f.andThen(g)runsffirst, then passes the result tog.f.compose(g)runsgfirst, then passes the result tof.
The order is the only difference, and it changes the answer.
Combining Predicates with and, or, and negate
A Predicate answers yes or no. You can join predicates the same way you join conditions with &&, ||, and !:
p.and(q)is true only when both are true.p.or(q)is true when at least one is true.p.negate()flips the answer.
Building Comparators with comparing and thenComparing
A comparator decides which of two items comes first when sorting. Comparator.comparing builds one from a method that pulls out a sort key, such as a word's length. thenComparing adds a tie-breaker for items whose keys are equal.
A Worked Example
This program uses all three kinds of composition.
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.function.Function;
import java.util.function.Predicate;
public class Composition {
public static void main(String[] args) {
Function<Integer, Integer> doubleIt = x -> x * 2;
Function<Integer, Integer> addThree = x -> x + 3;
System.out.println(doubleIt.andThen(addThree).apply(5)); // (5 * 2) + 3 = 13
System.out.println(doubleIt.compose(addThree).apply(5)); // (5 + 3) * 2 = 16
Predicate<String> nonEmpty = s -> !s.isEmpty();
Predicate<String> isShort = s -> s.length() < 5;
System.out.println(nonEmpty.and(isShort).test("cat")); // true
System.out.println(isShort.negate().test("cat")); // false
List<String> words = Arrays.asList("pear", "fig", "apple", "kiwi");
words.sort(Comparator.comparing(String::length)
.thenComparing(Comparator.naturalOrder()));
System.out.println(words); // [fig, kiwi, pear, apple]
}
}Here is what happens in the sort. The words are first ordered by length. "kiwi" and "pear" both have 4 letters, so thenComparing(Comparator.naturalOrder()) breaks the tie by putting them in alphabetical order.
| Method | Belongs to | What it builds |
|---|---|---|
| `andThen` | `Function` | Run this, then the other |
| `compose` | `Function` | Run the other, then this |
| `and`, `or`, `negate` | `Predicate` | Combined yes/no test |
| `comparing`, `thenComparing` | `Comparator` | Sort rule with tie-breakers |
Exercise
Using doubleIt and addThree from the example, what does addThree.andThen(doubleIt).apply(1) print?
Show answer
8. addThree runs first (1 + 3 = 4), then doubleIt runs (4 * 2 = 8).
Exercise
Using nonEmpty and isShort from the example, what does nonEmpty.or(isShort).test("") return, and why?
Show answer
true. nonEmpty is false for the empty string, but isShort is true because its length 0 is less than 5. With or, one true answer is enough.