00:00

Method References in Java 8

Last updated: · Standard (Java 8)

A method reference is a shorter way to write a lambda expression that only calls an existing method. It uses the double-colon operator, as in String::length, and was introduced in Java 8 together with lambdas.

You will learn the four kinds of method references, how the compiler maps each one to a functional interface, and when a lambda is the better choice.

1. Why Use Method References?

Many lambdas do nothing except forward their arguments: s -> s.length() or x -> System.out.println(x). A method reference names the method directly, which is shorter and often easier to read, especially in stream pipelines.

2. The Four Kinds of Method References

KindSyntaxEquivalent lambda
Static methodInteger::parseInts -> Integer.parseInt(s)
Instance method of a particular object (bound)prefix::concats -> prefix.concat(s)
Instance method of an arbitrary object (unbound)String::toUpperCases -> s.toUpperCase()
ConstructorArrayList::new() -> new ArrayList<>()

In the unbound form, the first parameter becomes the object the method is called on. That is why String::equalsIgnoreCase fits a BiFunction<String, String, Boolean>.

3. Practical Examples

Example 1: All four kinds in one program

FourKinds.java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Supplier;

public class FourKinds {
    static boolean isLongWord(String s) {
        return s.length() > 5;
    }

    public static void main(String[] args) {
        List<String> words = Arrays.asList("lambda", "java", "stream", "map", "optional");

        // 1. Static method:                 ClassName::staticMethod
        words.stream().filter(FourKinds::isLongWord).forEach(System.out::println);

        // 2. Instance method of a particular object:  object::method
        String prefix = "tag-";
        Function<String, String> addPrefix = prefix::concat;
        System.out.println(addPrefix.apply("java"));

        // 3. Instance method of an arbitrary object of a type:  ClassName::instanceMethod
        BiFunction<String, String, Boolean> sameIgnoreCase = String::equalsIgnoreCase;
        System.out.println(sameIgnoreCase.apply("JAVA", "java"));

        // 4. Constructor:                   ClassName::new
        Supplier<List<String>> listFactory = ArrayList::new;
        List<String> basket = listFactory.get();
        basket.add("apple");
        System.out.println(basket);
    }
}
Output
lambda
stream
optional
tag-java
true
[apple]

Example 2: The same pipeline with lambdas and references

Both pipelines produce the same list. The method-reference version splits the work into small named steps: create a ticket, read its code, convert to upper case.

LambdaVsReference.java
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class LambdaVsReference {
    static class Ticket {
        private final String code;

        Ticket(String code) {
            this.code = code;
        }

        String getCode() {
            return code;
        }
    }

    public static void main(String[] args) {
        List<String> codes = Arrays.asList("t-101", "t-205", "t-330");

        // Lambda versions
        List<Ticket> tickets1 = codes.stream().map(c -> new Ticket(c)).collect(Collectors.toList());
        List<String> upper1 = tickets1.stream().map(t -> t.getCode().toUpperCase()).collect(Collectors.toList());

        // Same logic with method references, split into small steps
        List<Ticket> tickets2 = codes.stream().map(Ticket::new).collect(Collectors.toList());
        List<String> upper2 = tickets2.stream()
                .map(Ticket::getCode)
                .map(String::toUpperCase)
                .collect(Collectors.toList());

        System.out.println(upper1);
        System.out.println(upper2);
        System.out.println("Same result: " + upper1.equals(upper2));
    }
}
Output
[T-101, T-205, T-330]
[T-101, T-205, T-330]
Same result: true

4. How a Method Reference Is Resolved

Resolving String::toUpperCase against Function<String, String> The compiler looks at the target type Function<String, String>, sees that apply takes one String, and treats the first argument as the receiver of toUpperCase. String::toUpperCase method reference Target type Function<String,String> apply(s) one String argument s.toUpperCase() call made at run time
Figure 1: Like a lambda, a method reference only gets its meaning from the functional interface it is assigned to.

5. Important Points and Best Practices

  • Use a method reference when the lambda only calls one method with the same arguments; otherwise keep the lambda.
  • A bound reference such as prefix::concat evaluates prefix once, when the reference is created. If prefix is null, the NullPointerException happens at that moment.
  • Overloaded methods can make a reference ambiguous; write a lambda with explicit types if the compiler cannot choose.
  • Constructor references also work for arrays: String[]::new is handy with toArray.

6. Summary

  • A method reference is shorthand for a lambda that calls one existing method.
  • There are four kinds: static, bound instance, unbound instance and constructor.
  • The target functional interface decides how arguments are passed.
  • Prefer references for simple forwarding and lambdas for anything more complex.

Related Tutorials

7. References