revert MapMax

This commit is contained in:
press0@gmail.com 2022-11-08 07:49:28 -06:00
parent 57b666b085
commit 7d1c17443b

View File

@ -1,11 +1,7 @@
package com.baeldung.map.mapmax; package com.baeldung.map.mapmax;
import java.util.Collections; import java.util.*;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.Optional;
public class MapMax { public class MapMax {
@ -32,12 +28,15 @@ public class MapMax {
.compareTo(e2.getValue()); .compareTo(e2.getValue());
} }
}); });
return maxEntry.getValue(); return maxEntry.getValue();
} }
public <K, V extends Comparable<V>> V maxUsingCollectionsMaxAndLambda(Map<K, V> map) { public <K, V extends Comparable<V>> V maxUsingCollectionsMaxAndLambda(Map<K, V> map) {
Entry<K, V> maxEntry = Collections.max(map.entrySet(), (Entry<K, V> e1, Entry<K, V> e2) -> e1.getValue() Entry<K, V> maxEntry = Collections.max(map.entrySet(), (Entry<K, V> e1, Entry<K, V> e2) -> e1.getValue()
.compareTo(e2.getValue())); .compareTo(e2.getValue()));
return maxEntry.getValue(); return maxEntry.getValue();
} }
@ -49,18 +48,22 @@ public class MapMax {
} }
public <K, V extends Comparable<V>> V maxUsingStreamAndLambda(Map<K, V> map) { public <K, V extends Comparable<V>> V maxUsingStreamAndLambda(Map<K, V> map) {
Optional<Entry<K, V>> maxEntry = map.entrySet() Optional<Entry<K, V>> maxEntry = map.entrySet()
.stream() .stream()
.max((Entry<K, V> e1, Entry<K, V> e2) -> e1.getValue() .max((Entry<K, V> e1, Entry<K, V> e2) -> e1.getValue()
.compareTo(e2.getValue())); .compareTo(e2.getValue()));
return maxEntry.get().getValue(); return maxEntry.get()
.getValue();
} }
public <K, V extends Comparable<V>> V maxUsingStreamAndMethodReference(Map<K, V> map) { public <K, V extends Comparable<V>> V maxUsingStreamAndMethodReference(Map<K, V> map) {
Optional<Entry<K, V>> maxEntry = map.entrySet() Optional<Entry<K, V>> maxEntry = map.entrySet()
.stream() .stream()
.max(Comparator.comparing(Map.Entry::getValue)); .max(Comparator.comparing(Map.Entry::getValue));
return maxEntry.get() return maxEntry.get()
.getValue(); .getValue();
} }