Modern Java 8+ Features · Lambdas and Functional Interfaces

Functional Interfaces: Predicate, Function, Consumer, Supplier

Java's four everyday lambda types: test a value, transform it, use it, or make one. Combine them with andThen.

FunctionalInterfacesDemo.java

import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;

public class FunctionalInterfacesDemo {
    public static void main(String[] args) {
        Predicate<Integer> isEven = n -> n % 2 == 0;          // takes a value, answers true/false
        Function<Integer, Integer> square = n -> n * n;       // takes a value, returns a value
        Consumer<String> shout = s -> System.out.println(s.toUpperCase());  // takes a value, returns nothing
        Supplier<String> greeting = () -> "hello";             // takes nothing, returns a value

        boolean even = isEven.test(4);
        int sq = square.apply(5);
        shout.accept(greeting.get());
        Function<Integer, Integer> squarePlusOne = square.andThen(n -> n + 1);
        int combined = squarePlusOne.apply(3);
        System.out.println(even + " " + sq + " " + combined);
    }
}

Step by step

  1. Predicate: takes a value and answers true or false.
  2. Function: takes a value and returns a new one.
  3. Consumer: takes a value and returns nothing.
  4. Supplier: takes nothing and returns a value.
  5. test runs the Predicate: is 4 even?
  6. Predicate: takes a value and answers true or false.
  7. The value it returned, true, is stored in even.
  8. apply runs the Function on 5.
  9. Function: takes a value and returns a new one.
  10. The value it returned, 25, is stored in sq.
  11. Line runs: shout.accept(greeting.get()).
  12. Supplier: takes nothing and returns a value.
  13. Java calls lambda$main$2(), with s = "hello". It gets its own variables on the stack.
  14. Consumer: takes a value and returns nothing.
  15. andThen builds a new Function: square first, then add one.
  16. Java calls lambda$main$1(), with n = 3. It gets its own variables on the stack.
  17. Function: takes a value and returns a new one.
  18. lambda$main$4() has finished, so its variables are gone.
  19. The value it returned, 10, is stored in combined.
  20. It prints true 25 10.
  21. true, 25 and 10 (3² + 1). Four shapes of lambda cover most everyday needs.