Skip to main content
Java 8 (LTS) · Topic 4 of 12

Method references

Definition​

A method reference is a shorter lambda that just calls an existing method, written Class::method. Use it when the lambda would only pass its argument straight to that method.

Example code​

Replacing small lambdas with method references

import java.util.List;

class Demo {
public static void main(String[] args) {
List<String> names = List.of("asha", "ravi", "meera");

names.stream().map(s -> s.toUpperCase()).forEach(s -> System.out.println(s)); // lambdas
names.stream().map(String::toUpperCase).forEach(System.out::println); // same, shorter

// other kinds: static method and constructor
List<Integer> numbers = List.of("1", "2", "3").stream().map(Integer::parseInt).toList();
System.out.println(numbers);
}
}

// Output:
// ASHA
// RAVI
// MEERA
// ASHA
// RAVI
// MEERA
// [1, 2, 3]

Finished this page? Track your progress (saved only in your browser).