 
 Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to implement an instance method reference using a class name in Java?
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
Advertisements
                    