Method references is a feature introduced in Java 8 that provides a shorthand syntax for referring to a method as a lambda expression. Method references allow us to pass a method as a parameter to a functional interface, instead of having to write a lambda expression that calls the method. Here are some basics of method references in Java:
1. Types of Method References: There are four types of method references in Java:
– Reference to a static method: `ClassName::staticMethodName`
– Reference to an instance method of an object of a particular type: `objectName::instanceMethodName`
– Reference to an instance method of an arbitrary object of a particular type: `ClassName::instanceMethodName`
– Reference to a constructor: `ClassName::new`
For example, to create a reference to the `toUpperCase()` method of the `String` class, we can use the following method reference:
FunctiontoUpper = String::toUpperCase;
This is equivalent to using a lambda expression:
FunctiontoUpper = s -> s.toUpperCase();
2. Method Reference Examples: Here are some examples of using method references in Java:
– Reference to a static method:
Listnumbers = Arrays.asList(1, 2, 3, 4, 5); numbers.stream().forEach(System.out::println);
Here, the `forEach()` method is passed a method reference to the `println()` method of the `System` class.
– Reference to an instance method of an object of a particular type:
Listnames = Arrays.asList("Alice", "Bob", "Charlie"); names.stream().map(String::length).forEach(System.out::println);
Here, the `map()` method is passed a method reference to the `length()` method of the `String` class.
– Reference to an instance method of an arbitrary object of a particular type:
Listnames = Arrays.asList("Alice", "Bob", "Charlie"); Collections.sort(names, String::compareToIgnoreCase);
Here, the `sort()` method is passed a method reference to the `compareToIgnoreCase()` method of the `String` class.
– Reference to a constructor:
Supplier> listSupplier = ArrayList::new; List
list = listSupplier.get();
Here, the `listSupplier` function creates a reference to the constructor of the `ArrayList` class.
Method references can simplify and optimize the use of lambda expressions in Java 8. By understanding the basics of method references and their various forms, you can write more efficient and effective code that can manipulate and process data in your applications with fewer lines of code.