What is method reference in Java?
Answer:
Explanation:
A method reference in Java is a shorthand notation for a lambda expression that executes just one method. It is a way to refer to methods of a class or object directly, without invoking them. Method references make the code more readable and concise, especially when the lambda expression simply calls an existing method. Here is an example:
List<String> names = Arrays.asList("Alice", "Bob", "Charlie"); names.forEach(System.out::println);
In this example, System.out::println
is a method reference that refers to the println
method of the System.out
object. It is equivalent to the lambda expression x -> System.out.println(x)
, but is more concise.
Method references are a powerful feature in Java, enabling developers to write more concise and expressive code. They are particularly useful when working with the Stream API and other functional programming constructs, where method references can simplify the code and improve readability.