0
0
JavaHow-ToBeginner · 3 min read

How to Use Method Reference in Java: Simple Guide

In Java, a method reference is a shorthand syntax to call a method directly using :: operator instead of a lambda expression. It makes code simpler and more readable by referring to existing methods by name. You can use method references for static methods, instance methods, or constructors.
📐

Syntax

Method references use the :: operator to refer to methods by name. There are four main types:

  • Static method reference: ClassName::staticMethodName
  • Instance method reference of a particular object: instance::instanceMethodName
  • Instance method reference of an arbitrary object of a type: ClassName::instanceMethodName
  • Constructor reference: ClassName::new

This syntax replaces lambda expressions that just call a method.

java
Runnable r = System.out::println;
Supplier<String> s = String::new;
Function<String, Integer> f = Integer::parseInt;
💻

Example

This example shows how to use method references to print a list of names and convert strings to integers.

java
import java.util.*;
import java.util.function.*;

public class MethodReferenceExample {
    public static void main(String[] args) {
        List<String> names = Arrays.asList("Anna", "Bob", "Charlie");

        // Using method reference to print each name
        names.forEach(System.out::println);

        // Using method reference to convert strings to integers
        List<String> numbers = Arrays.asList("1", "2", "3");
        List<Integer> ints = new ArrayList<>();
        numbers.forEach(s -> ints.add(Integer.parseInt(s)));

        // Using method reference instead of lambda
        ints.clear();
        numbers.forEach(s -> ints.add(Integer.parseInt(s)));

        // Using method reference with map
        List<Integer> mappedInts = numbers.stream()
            .map(Integer::parseInt)
            .toList();

        System.out.println("Mapped integers: " + mappedInts);
    }
}
Output
Anna Bob Charlie Mapped integers: [1, 2, 3]
⚠️

Common Pitfalls

Common mistakes when using method references include:

  • Using method references when the lambda does more than just call a method (method references only work for simple calls).
  • Confusing instance method references of a particular object vs. arbitrary objects.
  • Trying to use method references with incompatible functional interfaces.

Example of wrong and right usage:

java
import java.util.*;
import java.util.function.*;

public class PitfallExample {
    public static void main(String[] args) {
        List<String> list = Arrays.asList("a", "b", "c");

        // Wrong: lambda does more than call method
        // list.forEach(s -> System.out.println(s.toUpperCase())); // works
        // list.forEach(System.out::println); // prints original strings, not uppercase

        // Right: use lambda when extra logic is needed
        list.forEach(s -> System.out.println(s.toUpperCase()));

        // Right: use method reference when just calling method
        list.forEach(System.out::println);
    }
}
Output
A B C a b c
📊

Quick Reference

Summary tips for method references:

  • Use ClassName::staticMethod for static methods.
  • Use instance::instanceMethod for instance methods of a specific object.
  • Use ClassName::instanceMethod for instance methods of any object of that class.
  • Use ClassName::new for constructors.
  • Use method references only when the lambda expression just calls a method.

Key Takeaways

Method references use :: to refer to existing methods and simplify lambda expressions.
They can refer to static methods, instance methods, or constructors.
Use method references only when the lambda just calls a method without extra logic.
Instance method references can be of a particular object or any object of a class.
Method references improve code readability and reduce boilerplate.