- Trending Categories
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
- Related Articles
- How to create a thread using method reference in Java?\n
- How to implement an instance method reference using a class name in Java?
- How to sort a list using Comparator with method reference in Java 8?\n
- Reference to a static method using method references in Java8
- How to implement LongPredicate using lambda and method reference in Java?
- How to implement LongSupplier using lambda and method reference in Java?
- How to implement DoubleUnaryOperator using lambda and method reference in Java?
- How to implement DoublePredicate using lambda and method reference in Java?
- How to implement LongBinaryOperator using lambda and method reference in Java?
- How to implement LongFunction using lambda and method reference in Java?
- How to implement DoubleSupplier using lambda and method reference in Java?
- How to implement IntToDoubleFunction using lambda and method reference in Java?
- How to implement IntToLongFunction using lambda and method reference in Java?
- How to implement LongToIntFunction using lambda and method reference in Java?
- How to implement LongToDoubleFunction using lambda and method reference in Java?

Advertisements