diff --git a/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/mapmax/MapMax.java b/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/mapmax/MapMax.java index 36b839ad5f..8c33c857ee 100644 --- a/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/mapmax/MapMax.java +++ b/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/mapmax/MapMax.java @@ -1,11 +1,7 @@ package com.baeldung.map.mapmax; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; +import java.util.*; import java.util.Map.Entry; -import java.util.Optional; public class MapMax { @@ -29,15 +25,18 @@ public class MapMax { Entry maxEntry = Collections.max(map.entrySet(), new Comparator>() { public int compare(Entry e1, Entry e2) { return e1.getValue() - .compareTo(e2.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())); + .compareTo(e2.getValue())); + return maxEntry.getValue(); } @@ -49,20 +48,24 @@ public class MapMax { } public > V maxUsingStreamAndLambda(Map map) { + Optional> maxEntry = map.entrySet() - .stream() - .max((Entry e1, Entry e2) -> e1.getValue() + .stream() + .max((Entry e1, Entry e2) -> e1.getValue() .compareTo(e2.getValue())); - return maxEntry.get().getValue(); + return maxEntry.get() + .getValue(); } public > V maxUsingStreamAndMethodReference(Map map) { + Optional> maxEntry = map.entrySet() - .stream() - .max(Comparator.comparing(Map.Entry::getValue)); + .stream() + .max(Comparator.comparing(Map.Entry::getValue)); + return maxEntry.get() - .getValue(); + .getValue(); } public static void main(String[] args) {