Method reference

To improve code readability of Lambda expressions for functions having a name method reference is used. Method references have been identified in four different categories:

  • Static method reference: For a static method isOdd, the method can be directly referenced as MethodReferenceExample::isOdd:
public static boolean isOdd(Integer n) { return n % 2 != 0; };
public static void main(String[] args) {
IntStream.range(1, 8).filter(MethodReferenceExample::isOdd).forEach(x->System.out.println(x));
}
  • Instance method reference: For referencing an instance method, the instance of the method can be called separated by a double colon (::). Here System.out is an instance of PrintStream whose method println is being called:
//Instance Method Reference
IntStream.range(1, 8).filter(x-> x%2==0).forEach(System.out::println);
  • Constructor reference: A constructor method reference can be called by adding the suffix new after :::
//Constructor Reference
TreeSet<String> hset= streamSupplier.get().collect(Collectors.toCollection(TreeSet::new));

 

  1. Instance method reference of an arbitrary object of a particular type: The following example is an instance method reference of an arbitrary object of a particular type:
System.out.println(" The sum of lengths are ::" + streamSupplier.get().map(x->x.length()).reduce(Integer::sum));

Type

Lambda form

Method reference

Comments

Static method reference

(a, b) -> Employee.data(a, b)

Employee::data

Employee class has a static method, data().

Instance method reference

(a, b) -> sb.get(a, b)

sb::get

The method get() is fetched using the instance object sb.

Constructor reference

()->{ return new Integer ();}

Integer::new

Constructor being called directly.

Instance method reference of an arbitrary object of a particular type

x->System.out.println(x)

System.out::println

A non-static method being called using a class name.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.143.255.36