- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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 find a maximum value in a collection using method reference in Java?
A method reference provides a way in the lambda expression to refer a method without executing it. It requires a target type context that consists of a compatible functional interface.
Syntax
<Class-Name> :: <Static-Method-Name>
In the below example, we can find out the maximum value of an ArrayList using method reference.
Example
import java.util.*; class MyClass { private int val; MyClass(int v) { val = v; } int getVal() { return val; } } public class MethodReferenceMaxValueTest { static int compareMaxValue(MyClass a, MyClass b) { return a.getVal() - b.getVal(); } public static void main(String args[]) { ArrayList<MyClass> al = new ArrayList<MyClass>(); al.add(new MyClass(10)); al.add(new MyClass(30)); al.add(new MyClass(25)); al.add(new MyClass(15)); al.add(new MyClass(40)); al.add(new MyClass(35)); MyClass maxValObj = Collections.max(al, MethodReferenceMaxValueTest :: compareMaxValue); System.out.println("Maximum value is: " + maxValObj.getVal()); } }
Output
Maximum value is: 40
Advertisements