Sub topic 3
Combining Small Functions into Bigger Ones
Small lambdas are easy to read. You can join them to build bigger behavior without writing one long method.
Composing Functions and Predicates
Function has two default methods for chaining. A default method is a method that an interface already implements for you.
f.andThen(g)runsffirst, theng.f.compose(g)runsgfirst, thenf.
Predicate has and, or, and negate for joining true/false tests.
A stream is a sequence of values that you process step by step. filter keeps the values that pass a test. map changes each value. collect gathers the results into a list.
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
import java.util.function.IntPredicate;
import java.util.function.Predicate;
import java.util.stream.Collectors;
public class Combine {
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)); // 13
System.out.println(doubleIt.compose(addThree).apply(5)); // 16
Predicate<String> isShort = s -> s.length() < 5;
Predicate<String> startsWithK = s -> s.startsWith("k");
List<String> words = Arrays.asList("kiwi", "apple", "fig", "kumquat");
List<String> picked = words.stream()
.filter(isShort.and(startsWithK))
.map(String::toUpperCase)
.collect(Collectors.toList());
System.out.println(picked); // [KIWI]
IntPredicate isEven = n -> n % 2 == 0; // uses int directly, no boxing
System.out.println(isEven.test(4)); // true
}
}Other Things Worth Knowing
| Topic | What to remember |
|---|---|
| `this` in a lambda | It means the object of the surrounding class. In an anonymous class, `this` means the anonymous object itself. |
| Primitive interfaces | `IntPredicate` and `IntBinaryOperator` work on `int` directly. They avoid boxing, which is the work of wrapping an `int` in an `Integer` object. |
| Checked exceptions | A checked exception is one the compiler forces you to handle. `Function.apply` cannot throw one, so catch it inside the lambda or wrap it in a `RuntimeException`. |
| Ambiguous overloads | Overloads are methods that share a name. If two of them accept different functional interfaces, the compiler may not be able to pick one. Fix this with a cast or explicit parameter types. |
| Under the hood | The compiler turns each lambda into an `invokedynamic` instruction instead of an extra class file. Do not compare lambdas with `==`. |
Exercise
Using doubleIt and addThree from the example, what does doubleIt.compose(addThree).apply(1) print?
Show answer
8. compose runs addThree first (1 + 3 = 4), then doubleIt (4 * 2 = 8).
Exercise
Write a Predicate<String> that is true when a word is NOT short, reusing isShort.
Show answer
Predicate<String> isLong = isShort.negate();