Method references, introduced in Java 8, are a way to refer to a method by its name instead of using a lambda expression.
Method references were introduced in java-8 alongside lambda expressions.
The programmer can use a method reference as a syntactic sugar for a lambda expression that would merely call that method, when its signature is compatible with the functional-interface type.
The syntax of a method reference closely matches a method invocation expression, but with a double colon (::
) replacing the dot (.
).
// static method reference:
ToIntFunction<String> parseInt = Integer::parseInt;
int i = parseInt.applyAsInt("123");
// instance method reference:
Consumer<Object> println = System.out::println;
println.accept("Hello world!");
// constructor method reference:
Supplier<Object> newObject = Object::new;
Object o = newObject.get();
// array creation method reference:
IntFunction<Number[]> newArray = Number[]::new;
Number[] a = newArray.apply(10);
When working with generics, type arguments may be provided explicitly or inferred.
Supplier<List<String>> listSupplier;
// explicit type argument for a class:
listSupplier = ArrayList<String>::new;
// inferred type argument for a class:
listSupplier = LinkedList::new;
// ^^^^^^^^^^
// note: not a raw type in this context!
// LinkedList<String> will be inferred.
// explicit type argument for a method:
listSupplier = Collections::<String>emptyList;
// inferred type argument for a method:
listSupplier = Collections::emptyList;
See also: