Skip to content
Lambdas and Functional Interfaces
step 1/5

Reading — step 1 of 5

Learn

~1 min readLambdas and Streams

A lambda is a short function value:

Function<Integer, Integer> square = n -> n * n;
square.apply(5);   // 25

Predicate<String> nonEmpty = s -> !s.isEmpty();
BiFunction<Integer, Integer, Integer> add = (a, b) -> a + b;
Consumer<String> print = s -> System.out.println(s);
Supplier<Double> rand = () -> Math.random();

A functional interface is any interface with exactly one abstract method. The standard ones live in java.util.function:

InterfaceSignature
Function<T, R>R apply(T)
Predicate<T>boolean test(T)
Consumer<T>void accept(T)
Supplier<T>T get()
BiFunction<T, U, R>R apply(T, U)

Method references are a shorter syntax for lambdas that just call an existing method:

// these are equivalent
list.forEach(s -> System.out.println(s));
list.forEach(System.out::println);

list.stream().map(s -> s.toUpperCase());
list.stream().map(String::toUpperCase);

Four kinds of method references:

  • Class::staticMethod
  • instance::method
  • Class::instanceMethod (the receiver becomes the first arg)
  • Class::new (constructor reference)

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…