In Java, method references are a shorthand syntax for calling methods via lambda expressions. There are four main types of method references:
✅ 1. Reference to a static method
Syntax: ClassName::staticMethodName
Example:
Function<String, Integer> parser = Integer::parseInt;
System.out.println(parser.apply("123")); // Output: 123
✅ 2. Reference to an instance method of a particular object
Syntax: instance::instanceMethodName
Example:
String greeting = "Hello, ";
Function<String, String> sayHello = greeting::concat;
System.out.println(sayHello.apply("Stanley")); // Output: Hello, Stanley
✅ 3. Reference to an instance method of an arbitrary object of a particular type
Syntax: ClassName::instanceMethodName
Used when the instance is supplied as the first parameter of the lambda.
Example:
List<String> names = Arrays.asList("Stanley", "Anna", "Bob");
Collections.sort(names, String::compareToIgnoreCase);
This is equivalent to:
(name1, name2) -> name1.compareToIgnoreCase(name2)
✅ 4. Reference to a constructor
Syntax: ClassName::new
Example:
Supplier<List<String>> listSupplier = ArrayList::new;
List<String> list = listSupplier.get();