On the left of the arrow are the parameters. On the right is the body, the work to do. With one parameter, you can drop the brackets. With a one line body, there's no return, and no curly braces.
For each runs a lambda on every item. Here, it prints each name. Sort takes a lambda that compares two names, ignoring case. Remove if removes names longer than three letters. And replace all changes every item. Run it. The names print, then sort alphabetically, then shrink to three, then turn into capitals.
Main.javajava
import java.util.*;public class Main { public static void main(String[] args) { List<String> names = new ArrayList<>(List.of("Zoe", "adam", "Mia", "bob")); names.forEach(n -> System.out.print(n + " ")); System.out.println(); names.sort((a, b) -> a.compareToIgnoreCase(b)); System.out.println(names); names.removeIf(n -> n.length() > 3); System.out.println(names); names.replaceAll(n -> n.toUpperCase()); System.out.println(names); }}
Output
Zoe adam Mia bob
[adam, bob, Mia, Zoe]
[bob, Mia, Zoe]
[BOB, MIA, ZOE]
A lambda can be stored in a variable. The variable's type says what shape of function it is. Function takes a value, and returns one. Binary operator takes two values of the same type. A longer lambda uses curly braces, and return. Then we call them, with run, and apply. Run it. Hello, eighty one, seven, and sixty.
Main.javajava
import java.util.function.*;public class Main { public static void main(String[] args) { Runnable hello = () -> System.out.println("Hello!"); Function<Integer, Integer> square = x -> x * x; BinaryOperator<Integer> add = (a, b) -> a + b; Function<Double, Double> withTax = price -> { double tax = price * 0.2; return price + tax; }; hello.run(); System.out.println(square.apply(9)); System.out.println(add.apply(3, 4)); System.out.println(withTax.apply(50.0)); }}
A lambda is a small function you can store, and pass around. Parameters, then an arrow, then the body. Next, the types that hold lambdas, functional interfaces.