Java Method References
What a Method Reference Is
A method reference is a shorthand for a lambda that does nothing except call one existing method. Instead of writing the lambda, you name the method with the :: operator:
s -> s.length() // lambda
String::length // method reference — same meaning
x -> System.out.println(x) // lambda
System.out::println // method reference
Like a lambda, a method reference has no type of its own; it becomes an instance of the functional interface expected by the context (its target type). The compiler checks that the referenced method's parameters and return type fit that interface's single abstract method.
Why use them: when a lambda only forwards its arguments to a method, the method reference is shorter and reads as a description of what is done (map(Enrollment::student) — "map each enrollment to its student") rather than how (map(e -> e.student())). It also encourages putting non-trivial logic in well-named methods instead of long lambdas.
The Four Kinds of Method Reference
| Kind | Syntax | Equivalent lambda | Example |
|---|---|---|---|
| Static method | ClassName::staticMethod | (args) -> ClassName.staticMethod(args) | Integer::parseInt |
| Instance method of a particular object (bound) | object::method | (args) -> object.method(args) | System.out::println, prefix::concat |
| Instance method of an arbitrary object of a type (unbound) | ClassName::instanceMethod | (obj, args) -> obj.instanceMethod(args) | String::length, String::startsWith |
| Constructor | ClassName::new, Type[]::new | (args) -> new ClassName(args) | ArrayList::new, Course::new, String[]::new |
import java.util.*;
import java.util.function.*;
public class Kinds {
record Course(String code, int fee) { }
static boolean isPremium(Course c) { return c.fee() >= 5000; }
public static void main(String[] args) {
Function<String, Integer> parse = Integer::parseInt;
Predicate<Course> premium = Kinds::isPremium;
String prefix = "GC-";
Predicate<String> hasPrefix = prefix::equals;
Function<String, String> addPrefix = prefix::concat;
Consumer<Object> print = System.out::println;
Function<String, Integer> length = String::length;
BiFunction<String, String, Boolean> startsWith = String::startsWith;
Function<Course, String> code = Course::code;
Supplier<List<String>> newList = ArrayList::new;
BiFunction<String, Integer, Course> makeCourse = Course::new;
IntFunction<String[]> newArray = String[]::new;
print.accept(parse.apply("42") + 1);
print.accept(premium.test(new Course("DJ", 5999)));
print.accept(hasPrefix.test("GC-") + " " + addPrefix.apply("1001"));
print.accept(length.apply("Chennai") + " " + startsWith.apply("Coimbatore", "Coim"));
Course c = makeCourse.apply("JAVA", 4999);
print.accept(code.apply(c) + " " + c);
List<String> list = newList.get();
list.add("x");
print.accept(list + " " + newArray.apply(3).length);
}
}
Output:
43
true
true GC-1001
7 true
JAVA Course[code=JAVA, fee=4999]
[x] 3
1. Static method references
Integer::parseInt matches Function<String, Integer>: the function's argument is passed to parseInt. Kinds::isPremium refers to your own static method — a good way to give a condition a name and reuse it.
2. Bound instance method references — object::method
The object is fixed when the reference is created; the function's arguments become the method's arguments:
prefix::equals→s -> prefix.equals(s)prefix::concat→s -> prefix.concat(s), giving"GC-1001"System.out::println→x -> System.out.println(x), whereSystem.outis the bound object
Inside a class, this::methodName and super::methodName refer to methods of the current object or its parent class.
3. Unbound instance method references — ClassName::instanceMethod
No object is fixed. The first argument of the function becomes the object the method is called on, and any remaining arguments are passed as parameters:
String::length→s -> s.length()(one argument: the receiver)String::startsWith→(s, prefix) -> s.startsWith(prefix)(two arguments: receiver + parameter)Course::code→c -> c.code()— the most common use, extracting a property
The syntax looks like a static reference, which is confusing at first. The rule: if the method is an instance method and no object is given, the object comes from the first argument.
4. Constructor references — ClassName::new
ArrayList::newas aSupplier<List<String>>calls the no-argument constructor.Course::newas aBiFunction<String, Integer, Course>calls the record's two-argument constructor. Which constructor is used depends on the target type's parameters.String[]::newas anIntFunction<String[]>creates an array of the given length — this is whatstream.toArray(String[]::new)andlist.toArray(String[]::new)use.
Method References versus Lambdas: Two Differences
Method references and lambdas aren't always exactly equivalent. Two behaviours matter in practice:
import java.util.function.*;
public class Bound {
static class Counter {
private final String name;
private int value;
Counter(String name) { this.name = name; }
int next() { return ++value; }
public String toString() { return name; }
}
public static void main(String[] args) {
Counter current = new Counter("orders");
Supplier<Integer> methodRef = current::next;
Supplier<Integer> lambda = () -> current.next();
System.out.println(methodRef.get() + " " + lambda.get() + " " + methodRef.get());
Counter[] holder = {new Counter("first")};
Supplier<String> boundOnce = holder[0]::toString;
Supplier<String> evaluatedEachTime = () -> holder[0].toString();
holder[0] = new Counter("second");
System.out.println("method ref: " + boundOnce.get() + ", lambda: " + evaluatedEachTime.get());
String missing = null;
Supplier<Integer> lazy = () -> missing.length();
System.out.println("lambda created fine");
try {
Supplier<Integer> eager = missing::length;
} catch (NullPointerException e) {
System.out.println("method ref on null receiver: NullPointerException at creation");
}
}
}
Output:
1 2 3
method ref: first, lambda: second
lambda created fine
method ref on null receiver: NullPointerException at creation
- Both call the same object's method when the receiver is a fixed variable:
methodRefandlambdasharecurrent, so the counter goes 1, 2, 3. - The receiver expression of a bound method reference is evaluated once, when the reference is created.
holder[0]::toStringcaptured the first counter; replacingholder[0]later doesn't affect it. The lambda evaluatesholder[0]every time it runs, so it sees the second counter. - A
nullreceiver fails immediately for a method reference.missing::lengththrowsNullPointerExceptionat the moment the reference is created. The lambda() -> missing.length()is created without problems and would fail only when called.
When a Method Reference Doesn't Fit
Ambiguous references
import java.util.function.*;
public class Ambig {
public static void main(String[] args) {
Function<Integer, String> f = Integer::toString;
}
}
Ambig.java:5: error: incompatible types: invalid method reference
Function<Integer, String> f = Integer::toString;
^
reference to toString is ambiguous
both method toString(int) in Integer and method toString() in Integer match
1 error
Integer::toString could be the static Integer.toString(int) (the argument as parameter) or the instance method toString() (the argument as receiver). Both fit Function<Integer, String>, so the compiler refuses to guess. Use a lambda (i -> i.toString()) or a different method (String::valueOf).
When to keep a lambda
Use a lambda instead of a method reference when:
- the call needs extra arguments or constants:
s -> s.startsWith("GC-")(there's no method reference for "startsWith with this fixed argument"); - the arguments are used in a different order or transformed:
(a, b) -> b.compareTo(a); - more than one method is called:
s -> s.strip().toLowerCase(); - the lambda reads more clearly —
x -> x * 2is clearer than any method reference.
Practical Example: A Results Report Built from Method References
Stream pipelines are where method references are used most. This report parses enrollment data, keeps students who passed, summarises each course, and lists students who need support — with each kind of method reference doing a specific job.
import java.util.*;
import java.util.function.*;
import java.util.stream.*;
public class Report {
record Enrollment(String student, String course, int score) {
static Enrollment parse(String line) {
String[] f = line.split(",");
return new Enrollment(f[0].strip(), f[1].strip(), Integer.parseInt(f[2].strip()));
}
boolean passed() { return score >= 50; }
}
record CourseSummary(String course, long students, double average, String topStudent) { }
static class Formatter {
private final int nameWidth;
Formatter(int nameWidth) { this.nameWidth = nameWidth; }
String line(CourseSummary s) {
return String.format("%-" + nameWidth + "s %2d students avg %5.1f top %s",
s.course(), s.students(), s.average(), s.topStudent());
}
}
public static void main(String[] args) {
String csv = """
Asha, Java, 91
Ravi, Java, 45
Meena, Django, 77
Kumar, Java, 68
Asha, Django, 88
Divya, Docker, 39
""";
List<Enrollment> all = csv.lines()
.filter(Predicate.not(String::isBlank))
.map(Enrollment::parse)
.toList();
Map<String, List<Enrollment>> byCourse = all.stream()
.filter(Enrollment::passed)
.collect(Collectors.groupingBy(Enrollment::course, TreeMap::new, Collectors.toList()));
Formatter fmt = new Formatter(8);
byCourse.entrySet().stream()
.map(e -> new CourseSummary(
e.getKey(),
e.getValue().size(),
e.getValue().stream().mapToInt(Enrollment::score).average().orElse(0),
e.getValue().stream().max(Comparator.comparingInt(Enrollment::score)).map(Enrollment::student).orElse("-")))
.map(fmt::line)
.forEach(System.out::println);
String[] failed = all.stream().filter(Predicate.not(Enrollment::passed)).map(Enrollment::student).toArray(String[]::new);
System.out.println("needs support: " + String.join(", ", failed));
Set<String> students = all.stream().map(Enrollment::student).collect(Collectors.toCollection(TreeSet::new));
System.out.println("students: " + students);
}
}
Output:
Django 2 students avg 82.5 top Asha
Java 2 students avg 79.5 top Asha
needs support: Ravi, Divya
students: [Asha, Divya, Kumar, Meena, Ravi]
Where each kind of reference appears:
| Reference | Kind | Role |
|---|---|---|
String::isBlank, Enrollment::passed, Enrollment::course, Enrollment::score, Enrollment::student | Unbound instance | Test or extract something from each element |
Enrollment::parse | Static | Turn each text line into an Enrollment |
fmt::line, System.out::println | Bound instance | Use a specific object — the formatter configured with a column width, and the console |
TreeMap::new, TreeSet::new, String[]::new | Constructor | Tell collectors and toArray which container to create |
How the pipeline works:
- Parsing.
csv.lines()splits the text block into lines;Predicate.not(String::isBlank)drops empty lines; the static factoryEnrollment::parseconverts each line. - Grouping. Students who passed are grouped by course into a
TreeMap(sorted keys). Divya's Docker enrollment failed, so Docker doesn't appear. - Summarising. For each course, a lambda builds a
CourseSummary— a lambda is the right choice here because it combines several values. Inside it, method references extract scores for the average and compare by score to find the top student. - Formatting.
fmt::lineis a bound reference to aFormatterobject that holds configuration (the column width). It's likeSystem.out::println: a particular object whose method is called for each element. - Arrays and sets.
toArray(String[]::new)produces a typedString[];toCollection(TreeSet::new)collects unique, sorted student names.
The result reads almost like a description of the report. That readability is the main reason to prefer method references wherever a lambda would only forward to an existing method.