typestar

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

  1. Function and Predicate are the shapes most lambdas take.
  2. x -> x * x implements the interface without a class.
  3. String::length names 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.

Type this snippet

Step 2 of 3 in Methods & lambdas, step 16 of 29 in Language basics.

← Previous Next →

Lambdas in other languages