From 027cbaf9f99beca000ee3a3e9fe58f49e6c2f77d Mon Sep 17 00:00:00 2001 From: "press0@gmail.com" Date: Sat, 8 Oct 2022 21:41:57 -0500 Subject: [PATCH] simplify with comparingByValue() --- .../java/com/baeldung/map/mapmax/MapMax.java | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 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 8c33c857ee..99b57b398a 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,7 +1,11 @@ package com.baeldung.map.mapmax; -import java.util.*; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.Map; import java.util.Map.Entry; +import java.util.Optional; public class MapMax { @@ -34,15 +38,14 @@ public class MapMax { public > V maxUsingCollectionsMaxAndLambda(Map map) { - Entry maxEntry = Collections.max(map.entrySet(), (Entry e1, Entry e2) -> e1.getValue() - .compareTo(e2.getValue())); + Entry maxEntry = Collections.max(map.entrySet(), Entry.comparingByValue()); return maxEntry.getValue(); } public > V maxUsingCollectionsMaxAndMethodReference(Map map) { - Entry maxEntry = Collections.max(map.entrySet(), Comparator.comparing(Map.Entry::getValue)); + Entry maxEntry = Collections.max(map.entrySet(), Entry.comparingByValue()); return maxEntry.getValue(); } @@ -51,8 +54,7 @@ public class MapMax { Optional> maxEntry = map.entrySet() .stream() - .max((Entry e1, Entry e2) -> e1.getValue() - .compareTo(e2.getValue())); + .max(Entry.comparingByValue()); return maxEntry.get() .getValue(); @@ -62,7 +64,7 @@ public class MapMax { Optional> maxEntry = map.entrySet() .stream() - .max(Comparator.comparing(Map.Entry::getValue)); + .max(Entry.comparingByValue()); return maxEntry.get() .getValue();