In Java, Method References provide a concise way to refer to methods or constructors using a compact syntax. They were introduced in Java 8 and are similar to Lambda expressions. A Method Reference is used to replace a lambda expression when it is being used to simply call an existing method or constructor.
The forEach() method is a method of the Iterable interface that is used to iterate through a collection. It takes an argument of Consumer type interface. This is a functional interface with only one abstract method called accept(). Since it is a functional interface, a lambda expression can be passed as an argument.
For example, let's consider the following code snippet:
javaList<Integer> al = Arrays.asList(10, 20, 15, 16);
al.forEach(x -> System.out.println(x));
In the above code, we have used a lambda expression to iterate through the ArrayList and print the elements. We can simplify the above code by using Method References. When a lambda expression is simply used for a pass-through operation, it can be replaced by a method reference.
For example, the above code can be simplified as follows:
javaList<Integer> al = Arrays.asList(10, 20, 15, 16);
al.forEach(System.out::println);
In the above code, we have used a Method Reference to replace the lambda expression. Here, the instance or object method is passed, hence the object name is used.
In addition, Method References can also be used to refer to static methods. For example, the following code snippet demonstrates how to use a Method Reference to call a static method:
javaList<Integer> al = Arrays.asList(10, 20, 7, 8);
al.forEach(GfG::printSquare);
// Static method
public static void printSquare(Integer x) {
System.out.println(x*x);
}
In the above code, we have used a Method Reference to call the static method printSquare().
Furthermore, Method References can be used with functional interfaces, such as the Comparator interface, to provide a more concise way of comparing objects. For instance, the following code compares two arrays of Strings ignoring the cases using the Arrays.equals() method and passing the Method Reference as the Comparator interface:
javaString a[] = {"GfG", "IDE", "Courses"};
String b[] = {"gfg", "ide", "courses"};
if(Arrays.equals(a, b, String::compareToIgnoreCase))
System.out.println("Yes");
else
System.out.println("No");
In conclusion, Method References are a powerful feature introduced in Java 8 that provide a concise way to refer to methods or constructors. They simplify code and make it more readable by reducing the number of lines of code and improving the syntax. By using Method References, we can make our code more efficient and maintainable.