Method References in 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
| Kind | Syntax | Equivalent lambda |
|---|---|---|
| Static method | Integer::parseInt | s -> Integer.parseInt(s) |
| Instance method of a particular object (bound) | prefix::concat | s -> prefix.concat(s) |
| Instance method of an arbitrary object (unbound) | String::toUpperCase | s -> s.toUpperCase() |
| Constructor | ArrayList::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
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);
}
}
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.
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));
}
}
[T-101, T-205, T-330] [T-101, T-205, T-330] Same result: true
4. How a Method Reference Is Resolved
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::concatevaluatesprefixonce, when the reference is created. Ifprefixisnull, theNullPointerExceptionhappens 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[]::newis handy withtoArray.
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
Frequently Asked Questions (FAQ)
Q1. What is the :: operator in Java?
It is the method reference operator added in Java 8. ClassName::method or object::method creates a functional interface instance that calls that method.
Q2. What are the four types of method references?
References to a static method, to an instance method of a particular object, to an instance method of an arbitrary object of a given type, and to a constructor.
Q3. Is a method reference faster than a lambda?
No meaningful difference. Both are implemented with invokedynamic. Choose whichever is clearer to read.
Q4. Can a method reference refer to a constructor with arguments?
Yes. Ticket::new fits Function<String, Ticket> if Ticket has a constructor that takes a String; the compiler picks the constructor that matches the functional interface.