0Pricing
Java Academy · Lesson

Static Method References

Replace lambdas that call static methods with ClassName::methodName references.

What Are Method References?

A method reference is a shorthand lambda that delegates to an existing method. Where a lambda would just call a single method, a method reference is cleaner and more readable.

import java.util.*;
import java.util.stream.*;

List<String> names = List.of("Alice", "Bob", "Carol");

// Lambda:
names.forEach(s -> System.out.println(s));

// Equivalent method reference:
names.forEach(System.out::println);

Static Method Reference Syntax

A static method reference has the form ClassName::staticMethodName. It can be used wherever a functional interface expects a method with the same signature.

import java.util.stream.*;

// Integer.parseInt(String) matches Function<String, Integer>
List<String> strs = List.of("1","2","3","4","5");
List<Integer> nums = strs.stream()
    .map(Integer::parseInt)  // replaces s -> Integer.parseInt(s)
    .collect(Collectors.toList());
System.out.println(nums); // [1, 2, 3, 4, 5]

All lessons in this course

  1. Static Method References
  2. Instance Method References on a Specific Instance
  3. Arbitrary-Instance Method References
  4. Constructor References
← Back to Java Academy