How to implement an instance method reference using a class name in Java?

Java 8Object Oriented ProgrammingProgramming

Method reference is a simplified form of the lambda expression. It can specify a class name or instance name followed by the method name. The "::" symbol can separate a method name from the name of an object or class.

An instance method reference refers to an instance method of any class. In the below example, we can implement an instance methods reference using the class name.

Syntax

<Class-Name>::<Instance-Method-Name>

Example

import java.util.*;;
import java.util.function.*;

public class ClassNameRefInstanceMethodTest {
   public static void main(String args[]) {
      List<Employee> empList = Arrays.asList(
         new Employee("Raja", 15000),
         new Employee("Adithya", 12000),
         new Employee("Jai", 9000),
         new Employee("Ravi", 19000),
         new Employee("Surya", 8500),
         new Employee("Chaitanya", 7500),
         new Employee("Vamsi", 14000)
      );
      Function<Employee, String> getEmployeeNameFunction = new Function<Employee, String>() {
         @Override
         public String apply(Employee e) {
            return e.getName();
         }
      };
      System.out.println("The list of employees whose salary greater than 10000:");
      empList.stream()
      .filter(e -> e.getSalary() > 10000)
      .map(Employee::getName)  // instance method reference "getName" using class name "Employee"
      .forEach(e -> System.out.println(e));
   }
}

// Employee class
class Employee {
   private String name;
   private int salary;
   public Employee(String name, int salary){
      this.name = name;
      this.salary = salary;
   }
   public String getName() {
      return name;
   }
   public int getSalary() {
      return salary;
   }
}

Output

The list of employees whose salary greater than 10000:
Raja
Adithya
Ravi
Vamsi
raja
Published on 30-Dec-2019 18:25:07
Advertisements