Codiqo

Learn Java · lesson 54 of 61 · about 9 minutes

Lambdas

Write short functions with -> and hand them to methods that need them.

What you'll learn

  • Write lambdas with one or more parameters
  • Store lambdas in Function, Predicate and BinaryOperator variables
  • Use lambdas with forEach and removeIf

The lost property box

The morning after the desk locked up, the cleaners hand in what they found in the screens, typed one item per line until done. Some lines are blank and some just say nothing, so those are thrown out; everything else is labelled in capitals and listed: Lost property: UMBRELLA PHONE SCARF, then 3 items in the box. Deciding what to throw out is a small yes-or-no function, and Java lets you write it in one line and hand it to the list.

A function in one line

A lambda is a short function without a name: x -> x * 2 takes x and gives back x * 2. With two parameters it's (a, b) -> a + b.

You've seen the arrow in switch. Here it means "given this, give back that". A lambda can be stored in a variable of a functional interface type from java.util.function:
- Function<Integer, Integer> takes one value and returns one: call it with apply
- Predicate<String> answers true or false: call it with test
- BinaryOperator<Integer> combines two values: call it with apply

Storing lambdas

import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.Predicate;

public class Main {
    public static void main(String[] args) {
        Function<Integer, Integer> square = x -> x * x;
        Predicate<String> isLong = s -> s.length() > 5;
        BinaryOperator<Integer> add = (a, b) -> a + b;
        System.out.println(square.apply(7));
        System.out.println(isLong.test("phoebe") + " " + isLong.test("tea"));
        System.out.println(add.apply(2, 3));
    }
}

Output

49
true false
5

Lambdas and lists

Lists have methods that take lambdas: forEach runs one for every item, and removeIf removes every item for which a lambda says true. replaceAll changes every item.

forEach, removeIf and replaceAll

import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<Integer> scores = new ArrayList<>(List.of(45, 72, 90, 38, 66));
        scores.removeIf(s -> s < 50);
        scores.replaceAll(s -> s + 5);
        scores.forEach(s -> System.out.print(s + " "));
        System.out.println();
    }
}

Output

77 95 71

A Predicate with a name

Predicate<String> nothing = s -> s.isEmpty() || s.equalsIgnoreCase("nothing"); keeps the rule in a variable with a name that says what it means, and lostItems.removeIf(nothing) hands it to the list, which calls test on every item for you. Each item is trimmed as it's read, so a line of spaces becomes empty and goes too. After that, replaceAll(s -> s.toUpperCase()) changes what's left and forEach prints it.

Tip

List.of(...) makes a list that can't be changed. Wrapping it in new ArrayList<>(...) gives you a copy you can removeIf and replaceAll.

Now try it yourself

This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.