Method Reference in Java Streams

In Java Streams, a method reference is a shorthand notation for a lambda expression representing a specific method. It provides a more concise way to express certain types of lambda expressions. Method references are especially useful when you want to use an existing method as a lambda expression, avoiding unnecessary boilerplate code.


There are four types of method references:

1) Reference to Static Method

// Lambda expression
nameList.stream().forEach(s -> System.out.println(s));
// Method reference
nameList.stream().forEach(System.out::println);

2) Reference to an Instance Method of a particular object:

// Lambda expression
nameList.stream().forEach(s -> members.validate(s));
// Method reference
nameList.stream().forEach(members::validate);

3) Reference to an Instance Method of an Arbitrary Object of a Particular Type:

List<String> countryName =
Arrays.asList("India", "America", "Russia", "China", "Brazil");
countryName.sort(String::compareToIgnoreCase);
countryName.forEach(System.out::println);

The equivalent lambda expression for the method reference String::compareToIgnoreCase would have the formal parameter list (String a, String b), where a and b are arbitrary names and both parameters need to be explicitly passed. While using a method reference is much more straight forward.

4) Reference to a Constructor.

You can use a method reference to refer to a constructor without instantiating the named class. This kind of method reference is known as a constructor reference. Its syntax is className::new

The only this this lambda expression does is to create a new object and we just reference a constructor of the class with the keyword new.

In each example

  •  The :: operator is used for method references.
  •  The first part of the reference is the class or object on which the method is called.
  •  The second part is the name of the method.


Happy Programming...!!!


Comments

Popular posts from this blog

PHP LARAVEL Directory Structure

PHP LARAVEL - Hello World Laravel