Lambda vs Method Reference

Which One to Use

  • Use a method reference when the lambda only forwards its arguments to one method: map(String::trim) reads better than map(s -> s.trim()).
  • Use a lambda when you add logic, pass extra arguments or the reference would be confusing: map(s -> s.substring(0, 3)).
  • Method references to your own well-named methods are great for readability: filter(this::isEligible).

Example

The same pipeline written with a long lambda vs a named method reference.

import java.util.*;

public class Main {
    public static void main(String[] args) {
        List<Integer> ages = List.of(15, 22, 17, 30, 65, 70);

        List<Integer> withLambda = ages.stream()
                .filter(a -> a >= 18 && a < 60)
                .toList();

        List<Integer> withReference = ages.stream()
                .filter(Main::isWorkingAge)
                .toList();

        System.out.println(withLambda);
        System.out.println(withReference);
    }

    static boolean isWorkingAge(int age) {
        return age >= 18 && age < 60;
    }
}

Output

[22, 30]
[22, 30]

Practice

Exercise: Rewrite names.stream().map(n -> n.length()).forEach(x -> System.out.println(x)) using only method references.

Show answer
names.stream().map(String::length).forEach(System.out::println);