How to find a maximum value in a collection using method reference in Java?

Java 8Object Oriented ProgrammingProgramming

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
raja
Updated on 11-Jul-2020 12:29:58

Advertisements