
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
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
Implement Instance Method of an Arbitrary Object Using Method Reference in Java
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]
Advertisements