Lambdas in Java
Functions as values, through one-method interfaces.
import java.util.function.Function;
import java.util.function.Predicate;
// a lambda implements a one-method interface
Function<Integer, Integer> square = x -> x * x;
Predicate<String> isLong = s -> s.length() > 5;
System.out.println(square.apply(9));
System.out.println(isLong.test("keyboard"));
// method references name an existing method as the implementation
Function<String, Integer> len = String::length;
System.out.println(len.apply("typestar"));
System.out.println(square.andThen(square).apply(2));
How it works
FunctionandPredicateare the shapes most lambdas take.x -> x * ximplements the interface without a class.String::lengthnames an existing method as the implementation.
The run, in numbers
- Lines
- 14
- Characters to type
- 510
- Tokens
- 118
- Three-star pace
- 85 tpm
At the three-star pace of 85 tokens a minute, this run takes about 83 seconds.
Step 2 of 3 in Methods & lambdas, step 16 of 29 in Language basics.