From 5eab831bb568a895ce056a627079be30cda5e6a7 Mon Sep 17 00:00:00 2001 From: "press0@gmail.com" Date: Sat, 8 Oct 2022 22:30:21 -0500 Subject: [PATCH] . --- .../java/com/baeldung/map/mapmax/MapMax.java | 35 ++++++++++--------- 1 file changed, 18 insertions(+), 17 deletions(-) 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 11443865c7..36b839ad5f 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,6 +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.Map.Entry; @@ -25,48 +26,48 @@ public class MapMax { public > V maxUsingCollectionsMax(Map map) { - Entry maxEntry = Collections.max(map.entrySet(), Entry.comparingByValue()); - + 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.comparingByValue()); - + 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(), Entry.comparingByValue()); + 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.comparingByValue()); + .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(Entry.comparingByValue()); - + .stream() + .max(Comparator.comparing(Map.Entry::getValue)); return maxEntry.get() - .getValue(); + .getValue(); } public static void main(String[] args) { - Map map = new HashMap<>(); + Map map = new HashMap(); map.put(1, 3); map.put(2, 4);