Arbitrary-Instance Method References
Reference an instance method without specifying the receiver — used heavily with Stream operations.
What Are Arbitrary-Instance References?
An arbitrary-instance method reference uses ClassName::instanceMethod. Here the first argument of the functional interface serves as the receiver — each element becomes the object on which the method is called.
import java.util.*;
import java.util.stream.*;
List<String> names = List.of("alice","bob","carol");
// String::toUpperCase — receiver is each list element
List<String> upper = names.stream()
.map(String::toUpperCase)
.collect(Collectors.toList());
System.out.println(upper); // [ALICE, BOB, CAROL]How the Receiver Is Resolved
For an arbitrary-instance reference Type::method, the functional interface's first parameter becomes this (the receiver):
// String::length matches Function<String, Integer>
// Equivalent to: s -> s.length()
Function<String, Integer> len = String::length;
System.out.println(len.apply("Java")); // 4
// String::isEmpty matches Predicate<String>
// Equivalent to: s -> s.isEmpty()
Predicate<String> isEmpty = String::isEmpty;
System.out.println(isEmpty.test("")); // trueAll lessons in this course
- Static Method References
- Instance Method References on a Specific Instance
- Arbitrary-Instance Method References
- Constructor References