Sub topic 10
Combining Small Functions into Bigger Ones
Earlier chapters showed how to write a lambda and store it in a variable of a functional interface type. This chapter shows how to join small lambdas into bigger ones. Java's standard interfaces have built-in helper methods for this, so you can build new behavior without writing a new lambda each time.
What Composition Means
Composition means building a new function out of smaller functions. Picture an assembly line. One worker paints a box, and the next worker puts a label on it. Each worker does one simple job. Together they finish the box.
In Java, a default method is a method in an interface that already has a body. You can call it on any object that implements the interface. Function, Predicate, Consumer, and Comparator all include default methods that combine one instance with another. The table lists the main ones.
| Interface | Method | What the new function does |
|---|---|---|
| `Function` | `andThen(g)` | Runs this function, then `g` on the result |
| `Function` | `compose(g)` | Runs `g` first, then this function on the result |
| `Predicate` | `and(p)` | True only if both tests are true |
| `Predicate` | `or(p)` | True if at least one test is true |
| `Predicate` | `negate()` | Flips true to false and false to true |
| `Consumer` | `andThen(c)` | Does this action, then action `c` |
| `Comparator` | `thenComparing(c)` | Breaks ties using a second rule |
| `Comparator` | `reversed()` | Sorts in the opposite order |
None of these methods change the original lambda. Each one returns a brand new object, and the originals stay the same.
Chaining Functions with andThen and compose
andThen and compose both join two Function objects. The only difference is the order in which they run.
import java.util.function.Function;
public class ChainFunctions {
public static void main(String[] args) {
Function<Integer, Integer> doubleIt = x -> x * 2;
Function<Integer, Integer> addThree = x -> x + 3;
// andThen: doubleIt runs first, then addThree
Function<Integer, Integer> doubleThenAdd = doubleIt.andThen(addThree);
System.out.println(doubleThenAdd.apply(5)); // (5 * 2) + 3 = 13
// compose: addThree runs first, then doubleIt
Function<Integer, Integer> addThenDouble = doubleIt.compose(addThree);
System.out.println(addThenDouble.apply(5)); // (5 + 3) * 2 = 16
// The original functions are unchanged
System.out.println(doubleIt.apply(5)); // 10
}
}A simple way to remember the order: a.andThen(b) reads left to right, so "do a, and then do b." a.compose(b) means "a is built on top of b," so b runs first.
Types must line up
The output type of the first function must match the input type of the second. Suppose length is a Function<String, Integer>. Then length.andThen(n -> n * 10) works, because the Integer coming out of length is what the second function takes in. The result is a Function<String, Integer>. If the types do not line up, the code will not compile.
Building a pipeline in a loop
Sometimes you don't know how many steps you need until the program runs. Function.identity() returns a function that gives back its input unchanged. It is a good starting point for a chain.
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
public class PipelineBuilder {
public static void main(String[] args) {
List<Function<String, String>> steps = new ArrayList<>();
steps.add(String::trim);
steps.add(String::toLowerCase);
steps.add(s -> s.replace(' ', '-'));
Function<String, String> pipeline = Function.identity();
for (Function<String, String> step : steps) {
pipeline = pipeline.andThen(step);
}
System.out.println(pipeline.apply(" Hello World ")); // hello-world
}
}Each pass through the loop wraps the chain in one more step. The final pipeline trims the text, lowercases it, and swaps spaces for dashes.
Combining Tests with Predicate
A Predicate answers a yes-or-no question. Its helper methods work like the words "and," "or," and "not."
import java.util.function.Predicate;
public class CombinePredicates {
public static void main(String[] args) {
Predicate<String> notNull = s -> s != null;
Predicate<String> nonEmpty = s -> !s.isEmpty();
Predicate<String> isShort = s -> s.length() < 5;
Predicate<String> startsWithA = s -> s.startsWith("a");
System.out.println(nonEmpty.and(isShort).test("cat")); // true
System.out.println(nonEmpty.and(isShort).test("")); // false
System.out.println(isShort.or(startsWithA).test("avocado")); // true
System.out.println(isShort.negate().test("cat")); // false
// Safe null check: nonEmpty never runs when notNull is false
Predicate<String> hasText = notNull.and(nonEmpty);
System.out.println(hasText.test(null)); // false
System.out.println(hasText.test("hi")); // true
}
}Short-circuiting and order
and and or short-circuit: they stop as soon as they know the answer. With and, if the first test is false, the second test never runs. That is why notNull.and(nonEmpty) is safe to call with null.
Running Actions in Sequence with Consumer
A Consumer does something with a value and returns nothing. Its andThen runs two actions one after the other on the same value.
import java.util.function.Consumer;
public class ChainConsumers {
public static void main(String[] args) {
Consumer<String> log = s -> System.out.println("Log: " + s);
Consumer<String> save = s -> System.out.println("Saved: " + s);
Consumer<String> logAndSave = log.andThen(save);
logAndSave.accept("order-1");
// Log: order-1
// Saved: order-1
}
}Consumer.andThen differs from Function.andThen in one way. Both consumers receive the same original value, because a consumer has no result to pass along.
Building Sort Orders with Comparator
A Comparator decides which of two items comes first. Comparator.comparing builds a comparator from a function that picks out a sort key. A sort key is the value you sort by, such as a word's length.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class CombineComparators {
public static void main(String[] args) {
List<String> words = new ArrayList<>(Arrays.asList("pear", "fig", "apple", "kiwi"));
// Shortest first; ties broken alphabetically
words.sort(Comparator.comparing(String::length)
.thenComparing(Comparator.naturalOrder()));
System.out.println(words); // [fig, kiwi, pear, apple]
// Longest first; ties still broken alphabetically
words.sort(Comparator.comparing(String::length)
.reversed()
.thenComparing(Comparator.naturalOrder()));
System.out.println(words); // [apple, kiwi, pear, fig]
}
}"kiwi" and "pear" both have four letters. The thenComparing step breaks that tie in alphabetical order. In the second sort, reversed() flips only the length rule, because it comes before thenComparing in the chain. Each call wraps everything to its left.
Common Mistakes
- Mixing up
andThenandcompose. If the result looks wrong, check which function runs first. - Expecting the original to change.
doubleIt.andThen(addThree)returns a new function. If you don't store the result or use it right away, nothing changes. - Wrong order in
Predicate.and. Put cheap or safety checks first so they can short-circuit. - Losing the type with
UnaryOperator.UnaryOperator.andThenreturns a plainFunction, not aUnaryOperator. Store the result in aFunction<T, T>variable.
Exercises
Exercise
Given Function<Integer, Integer> square = x -> x * x; and Function<Integer, Integer> minusOne = x -> x - 1;, what do square.andThen(minusOne).apply(4) and square.compose(minusOne).apply(4) print?
Show answer
square.andThen(minusOne) squares first, then subtracts one: 16 - 1 = 15. square.compose(minusOne) subtracts one first, then squares: 3 * 3 = 9.
Exercise
Write a single Predicate<String> named validName that is true only when the string is not null, is not empty, and is at most 10 characters long. It must not throw an exception for null.
Show answer
Predicate<String> notNull = s -> s != null; Predicate<String> nonEmpty = s -> !s.isEmpty(); Predicate<String> maxTen = s -> s.length() <= 10; Predicate<String> validName = notNull.and(nonEmpty).and(maxTen); Because notNull comes first and and short-circuits, the other tests never run on null.
Exercise
You have a List<String> of city names. Write a single sort call that orders them longest first, with cities of the same length in alphabetical order.
Show answer
cities.sort(Comparator.comparing(String::length).reversed().thenComparing(Comparator.naturalOrder())); The reversed() call flips only the length rule because it comes before thenComparing.