Core Java
19 — Lambdas & Functional Programming
Previous: 18 Generics · Next: 20 Streams & Optional
▶️ java pkg1core/core21FunctionalProgramming.java
Lambda expressions (Java 8+)
1Calculator add = (a, b) -> a + b;2Runnable task = () -> System.out.println("run");3Consumer<String> print = s -> System.out.println(s);A lambda implements a functional interface (exactly one abstract method).
Core functional interfaces
| Interface | Method | Use |
|---|---|---|
Supplier<T> |
get() |
Supply a value |
Consumer<T> |
accept(T) |
Act on a value |
Function<T,R> |
apply(T) |
Transform T → R |
Predicate<T> |
test(T) |
Boolean test |
BiFunction<T,U,R> |
apply(T,U) |
Two-arg function |
Method references
1Function<String, Integer> len = String::length;2Supplier<List<String>> factory = ArrayList::new;3list.forEach(System.out::println);Shorthand when lambda just calls one method.
Custom functional interface
1@FunctionalInterface2interface Calculator {3 int op(int a, int b);4}@FunctionalInterface is optional but catches mistakes.
Next → 20 Streams & Optional Related → 06 Streams
Source named in this chapter
- core21FunctionalProgrammingpkg1core/core21FunctionalProgramming.java