Java SE 8 Programmer II study materials
Java SE 8 Programmer II study resources

Java SE 8 Programmer II: Lambda Built-in Functional Interfaces

Java SE 8 Programmer II · Work through your exam, one topic at a time.

All guide sections

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), plus andThen. Function<T,R>: R apply(T), plus compose and andThen. BiFunction<T,U,R>: R apply(T,U).
  • Predicate<T>: boolean test(T), with and, or, negate; BiPredicate<T,U> takes two arguments.
  • UnaryOperator<T> extends Function<T,T>; BinaryOperator<T> extends BiFunction<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), and Type::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

  • andThen and compose run in opposite orders; exam questions swap them.
  • Function.identity() returns its argument; it is not x -> null.
  • Predicate returns boolean; Consumer returns void, so it cannot be used where a Function is required.
  • Captured local variables must be effectively final.
  • A lambda that throws a checked exception cannot target an interface whose method declares none.