Java Lambda Expression Method reference find the maximum value in a collection
// Use a method reference to help find the maximum value in a collection. import java.util.ArrayList; import java.util.Collections; import java.util.List; class My {/* ww w. j a v a 2 s. co m*/ private int val; My(int v) { val = v; } int getVal() { return val; } } public class Main { // A compare() method compatible with the one defined by Comparator<T>. static int compareMC(My a, My b) { return a.getVal() - b.getVal(); } public static void main(String args[]) { List<My> al = new ArrayList<My>(); al.add(new My(1)); al.add(new My(4)); al.add(new My(2)); al.add(new My(9)); al.add(new My(3)); al.add(new My(7)); // Find the maximum value in list using the compareMC() method. My maxValObj = Collections.max(al, Main::compareMC); System.out.println("Maximum value is: " + maxValObj.getVal()); } }