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:
| Interface | Signature |
|---|---|
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::staticMethodinstance::methodClass::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…