AI Hints
Home›Java Tutorial›Lambdas, Functional Interfaces and Method References
Java · Lesson 102 of 120

Method References

Point to a method.

⏱ 2 min read▶ Video at 2:10:44🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

When a lambda just calls one existing method, you can point to that method directly instead. That's a method reference, written with two colons.

  • A lambda that just calls a method
  • Point to it instead
  • Two colons

Four kinds

System dot out, colon colon, println, replaces the lambda that prints each word. String colon colon length refers to a method of each string. Main colon colon is even refers to our own static method. Compare to ignore case is used to sort. And array list colon colon new refers to a constructor. Run it. Every one works, exactly like the matching lambda.

Main.javajava
import java.util.*;
import java.util.function.*;
public class Main {
    static boolean isEven(int n) { return n % 2 == 0; }

    public static void main(String[] args) {
        List<String> words = new ArrayList<>(List.of("kiwi", "Fig", "banana"));
        words.forEach(System.out::println);
        Function<String, Integer> len = String::length;
        System.out.println(len.apply("hello"));
        Predicate<Integer> even = Main::isEven;
        System.out.println(even.test(10) + " " + even.test(7));
        words.sort(String::compareToIgnoreCase);
        System.out.println(words);
        Supplier<List<String>> maker = ArrayList::new;
        System.out.println("New list: " + maker.get());
    }
}
Output
kiwi
Fig
banana
5
true false
[banana, Fig, kiwi]
New list: []

Lambda or reference

Each method reference has a matching lambda. Use whichever reads more clearly.

Method referenceSame as
System.out::printlnx -> System.out.println(x)
String::lengths -> s.length()
Main::isEvenn -> Main.isEven(n)
ArrayList::new() -> new ArrayList<>()

Summary

A method reference, with two colons, points to an existing method or constructor. It's a shorter way to write a simple lambda. Next, streams.

Key takeaways
  • Class::method
  • obj::method
  • Class::new
Next up: Streams — process data step by step