package com.baeldung.map.mapmax; import java.util.*; import java.util.Map.Entry; public class MapMax { public > V maxUsingIteration(Map map) { Map.Entry maxEntry = null; for (Map.Entry entry : map.entrySet()) { if (maxEntry == null || entry.getValue() .compareTo(maxEntry.getValue()) > 0) { maxEntry = entry; } } return maxEntry.getValue(); } public > V maxUsingCollectionsMax(Map map) { Entry maxEntry = Collections.max(map.entrySet(), new Comparator>() { public int compare(Entry e1, Entry e2) { return e1.getValue() .compareTo(e2.getValue()); } }); return maxEntry.getValue(); } public > V maxUsingCollectionsMaxAndLambda(Map map) { Entry maxEntry = Collections.max(map.entrySet(), (Entry e1, Entry e2) -> e1.getValue() .compareTo(e2.getValue())); return maxEntry.getValue(); } public > V maxUsingCollectionsMaxAndMethodReference(Map map) { Entry maxEntry = Collections.max(map.entrySet(), Comparator.comparing(Map.Entry::getValue)); return maxEntry.getValue(); } public > V maxUsingStreamAndLambda(Map map) { Optional> maxEntry = map.entrySet() .stream() .max((Entry e1, Entry e2) -> e1.getValue() .compareTo(e2.getValue())); return maxEntry.get() .getValue(); } public > V maxUsingStreamAndMethodReference(Map map) { Optional> maxEntry = map.entrySet() .stream() .max(Comparator.comparing(Map.Entry::getValue)); return maxEntry.get() .getValue(); } public static void main(String[] args) { Map map = new HashMap(); map.put(1, 3); map.put(2, 4); map.put(3, 5); map.put(4, 6); map.put(5, 7); MapMax mapMax = new MapMax(); System.out.println(mapMax.maxUsingIteration(map)); System.out.println(mapMax.maxUsingCollectionsMax(map)); System.out.println(mapMax.maxUsingCollectionsMaxAndLambda(map)); System.out.println(mapMax.maxUsingCollectionsMaxAndMethodReference(map)); System.out.println(mapMax.maxUsingStreamAndLambda(map)); System.out.println(mapMax.maxUsingStreamAndMethodReference(map)); } }