Java 8 Method Reference and Constructor Reference

Method Reference

Method reference is an abbreviated syntax used with lambda expressions for invoking a method.

Double colon operator (::) is used to represent a method reference.

The syntax for the same is :

ClassName::MethodName

ClassName::instanceMethodName represents a method reference for an instance method of a class.
This creates a one-parameter lambda that invokes the instance method on the lambda’s argument and returns the method’s result.

objectName::instanceMethodName represents a method reference for an instance method that should be called on a specific object.
This creates a one-parameter lambda that invokes the instance method on the specified object—passing the lambda’s argument to the instance method—and returns the method’s result.

ClassName::staticMethodName represents a method reference for a static method of a class.
This creates a one-parameter lambda in which the lambda’s argument is passed to the specified a static method and the lambda returns the method’s result.

 

Example of using Method reference in lambda expression

We can loop through a List using a lambda forEach loop as follows :

List<String> countries = Arrays.asList("Germany", "England", "China",
    "Denmark", "Brazil", "France", "Australia");
countries.forEach(System.out::println);

This example prints the country names as :

Germany
England
China
Denmark
Brazil
France
Australia
 

Example of converting List of Strings to uppercase using method reference

List<String> countries = Arrays.asList("Germany", "England", "China",
    "Denmark", "Brazil", "France", "Australia");
countries.stream().map(String::toUpperCase)
    .forEach(System.out::println);

Output :

GERMANY
ENGLAND
CHINA
DENMARK
BRAZIL
FRANCE
AUSTRALIA
 

Constructor reference

Similar to method reference, we can use constructor reference instead of the traditional “new” syntax to create an instance.

ClassName::new represents a constructor reference.
This creates a lambda that invokes the no-argument constructor of the specified class to create and initialize a new object of that class.

Example : no-argument constructor

package com.topjavatutorial;

public class Employee {

  public Employee(){
    
  }

}


Supplier<Employee> supplier = Employee::new;
Employee e = supplier.get();

 

Example : one-parameter constructor

package com.topjavatutorial;

public class Employee {

  private String name;
  public Employee(String name){
    this.name = name;
  }

}

Function<String,Employee> function = Employee::new;
System.out.println(function.apply("John Doe"));

ClassName[]::new is a shortcut for creating an Array using the method reference notation.
This creates an array of provided type.

 

© 2016, https:. All rights reserved. On republishing this post, you must provide link to original post

Leave a Reply.. code can be added in <code> </code> tags