×

java · level 3 · unit 2 · lesson 1

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

A is a method you can pass around.

Some methods want behaviour as well as data. list.removeIf needs to know which items to remove. A lambda is that behaviour written as a value: price -> price > 50. It has no name and no return type, because Java works those out from where you use it.

Parameters go left of the , the body goes right. One parameter needs no brackets; none or two do: () -> 42, (a, b) -> a + b. A one-expression body hands back its value. A longer body uses curly brackets and return.

A lambda can read the variables in the method around it, but only ones: never given a new value after the first. Change one and Java stops you, because the lambda might run later, after the variable has moved on.

import java.util.ArrayList;
import java.util.List;
public class Main {
    public static void main(String[] args) {
        List<Integer> prices = new ArrayList<>(List.of(12, 80, 45, 120, 9));
        int limit = 50;
        prices.removeIf(price -> price > limit);
        prices.sort((a, b) -> b - a);
        prices.forEach(price -> System.out.println("Under budget: " + price));
    }
}

A comparator lambda answers like compareTo, so (a, b) -> b - a puts the biggest first.