Lambda Built-in Functional Interfaces
Lambda Built-in Functional Interfaces covers the java.util.function package, target typing, method references, and composing lambdas.
Core rules
Supplier<T>:T get().Consumer<T>:void accept(T), plusandThen.Function<T,R>:R apply(T), pluscomposeandandThen.BiFunction<T,U,R>:R apply(T,U).Predicate<T>:boolean test(T), withand,or,negate;BiPredicate<T,U>takes two arguments.UnaryOperator<T>extendsFunction<T,T>;BinaryOperator<T>extendsBiFunction<T,T,T>.- Primitive specializations avoid boxing:
IntPredicate,IntFunction<R>,ToIntFunction<T>,IntUnaryOperator,IntBinaryOperator,IntSupplier,IntConsumer. - A lambda needs a target type; the same expression can implement different interfaces only if the abstract method signature matches.
- Method references:
Type::staticMethod,instance::instanceMethod,Type::instanceMethod(first parameter becomes receiver), andType::new.
Worked example
Function<Integer,Integer> inc = x -> x + 1;
Function<Integer,Integer> dbl = x -> x * 2;
inc.compose(dbl).apply(3) gives 7: dbl runs first, then inc.
inc.andThen(dbl).apply(3) gives 8: inc runs first, then dbl.
For predicates, p.negate().test(x) is !p.test(x); p.and(q) short-circuits.
Traps
andThenandcomposerun in opposite orders; exam questions swap them.Function.identity()returns its argument; it is notx -> null.Predicatereturnsboolean;Consumerreturnsvoid, so it cannot be used where aFunctionis required.- Captured local variables must be effectively final.
- A lambda that throws a checked exception cannot target an interface whose method declares none.