How to implement an instance method of an arbitrary object using method reference in Java?

Java 8Object Oriented ProgrammingProgramming

A method reference is a new feature in Java 8, which is related to Lambda Expression. It can allow us to reference constructors or methods without executing them. The method references and lambda expressions are similar in that they both require a target type that consists of a compatible functional interface.

Syntax

Class :: instanceMethodName

Example

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

public class ArbitraryObjectMethodRefTest {
   public static void main(String[] args) {
      List<Person> persons = new ArrayList<Person>();
      persons.add(new Person("Raja", 30));
      persons.add(new Person("Jai", 25));
      persons.add(new Person("Adithya", 20));
      persons.add(new Person("Surya", 35));
      persons.add(new Person("Ravi", 32));
      List ages = ArbitraryObjectMethodRefTest.listAllAges(persons, Person :: getAge);
      System.out.println("Printing out all ages: \n" + ages);
   }
   private static List listAllAges(List person, Function<Person, Integer> f) {
      List result = new ArrayList();
      person.forEach(x -> result.add(f.apply((Person)x)));
      return result;
   }
   private static class Person {
      private final String name;
      private final int age;
      public Person(String name, int age) {
         this.name = name;
         this.age = age;
      }
      public String getName() {
         return name;
      }
      public int getAge() {
         return age;
      }
   }
}

Output

Printing out all ages:
[30, 25, 20, 35, 32]
raja
Published on 17-Dec-2019 18:18:41
Advertisements