If you have any query feel free to chat us!
Happy Coding! Happy Learning!
Method references in Java provide a shorthand notation for referring to methods or constructors. They are a concise and readable way to pass methods as arguments to higher-order functions or to use them in functional interfaces. Method references make your code more expressive and allow you to reuse existing methods as lambda expressions.
Method references are typically used in the context of functional interfaces, where a single abstract method needs to be implemented. There are four types of method references:
ClassName::staticMethodName
Example:
javaCopy code
// Using a method reference to refer to the static method Integer.parseInt()
Function<String, Integer> parser = Integer::parseInt;
int number = parser.apply("123"); // number = 123
objectReference::instanceMethodName
Example:
javaCopy code
// Using a method reference to refer to the instance method of an object
String str = "Hello, World!";
Consumer<String> printString = System.out::println;
printString.accept(str); // Output: Hello, World!
ClassName::instanceMethodName
Example:
javaCopy code
// Using a method reference to refer to the instance method of an object of a specific type
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
names.forEach(String::toUpperCase);
ClassName::new
Example:
javaCopy code
// Using a method reference to refer to a constructor
Supplier<List<String>> listSupplier = ArrayList::new;
List<String> newList = listSupplier.get();
In each type of method reference, the method signature (number and types of arguments) should match the functional interface's abstract method signature.
Method references can simplify your code when the lambda expression's sole purpose is to call an existing method with the same signature as the functional interface's abstract method. They are particularly useful when working with streams and functional programming constructs.
Remember that method references are not always a replacement for lambda expressions. They are an alternative when you have existing methods with compatible signatures. You can choose between lambda expressions and method references based on readability and code elegance.
Comments: 0