Category : Java | Sub Category : Java8 Features | By Prasad Bonam Last updated: 2023-11-13 04:28:00 Viewed : 234
Method references in Java provide a concise way to express lambda expressions when the lambda body simply calls an existing method. They enable you to refer to a method without having to define a corresponding lambda expression. Method references are often more readable and expressive than equivalent lambda expressions, especially when working with existing methods or constructors.
There are four types of method references in Java:
Reference to a Static Method:
ClassName::staticMethodName
java// Lambda expression
Function<String, Integer> lengthFunction = s -> s.length();
// Method reference
Function<String, Integer> lengthFunctionReference = String::length;
Reference to an Instance Method of a Particular Object:
instance::instanceMethodName
java// Lambda expression
String prefix = "Hello, ";
Function<String, String> greetFunction = s -> prefix.concat(s);
// Method reference
String prefixReference = "Hello, ";
Function<String, String> greetFunctionReference = prefixReference::concat;
Reference to an Instance Method of an Arbitrary Object of a Particular Type:
ClassName::instanceMethodName
java// Lambda expression
Comparator<String> lengthComparator = (s1, s2) -> Integer.compare(s1.length(), s2.length());
// Method reference
Comparator<String> lengthComparatorReference = Comparator.comparing(String::length);
Reference to a Constructor:
ClassName::new
java// Lambda expression
Supplier<List<String>> listSupplier = () -> new ArrayList<>();
// Method reference
Supplier<List<String>> listSupplierReference = ArrayList::new;
Method references are especially useful when working with the Stream API, making code more concise and readable. Here is an example using a method reference with the Stream API:
javaList<String> words = Arrays.asList("apple", "banana", "orange");
// Lambda expression
words.stream().map(s -> s.toUpperCase()).forEach(System.out::println);
// Method reference
words.stream().map(String::toUpperCase).forEach(System.out::println);
In the above example, String::toUpperCase
is a method reference, which is a more concise way to express the transformation of each element in the stream to its uppercase form.