revert MapMax

This commit is contained in:
press0@gmail.com 2022-11-08 07:49:28 -06:00
parent 57b666b085
commit 7d1c17443b
1 changed files with 16 additions and 13 deletions

View File

@ -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<K, V> maxEntry = Collections.max(map.entrySet(), new Comparator<Entry<K, V>>() {
public int compare(Entry<K, V> e1, Entry<K, V> e2) {
return e1.getValue()
.compareTo(e2.getValue());
.compareTo(e2.getValue());
}
});
return maxEntry.getValue();
}
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()
.compareTo(e2.getValue()));
.compareTo(e2.getValue()));
return maxEntry.getValue();
}
@ -49,20 +48,24 @@ public class MapMax {
}
public <K, V extends Comparable<V>> V maxUsingStreamAndLambda(Map<K, V> map) {
Optional<Entry<K, V>> maxEntry = map.entrySet()
.stream()
.max((Entry<K, V> e1, Entry<K, V> e2) -> e1.getValue()
.stream()
.max((Entry<K, V> e1, Entry<K, V> e2) -> e1.getValue()
.compareTo(e2.getValue()));
return maxEntry.get().getValue();
return maxEntry.get()
.getValue();
}
public <K, V extends Comparable<V>> V maxUsingStreamAndMethodReference(Map<K, V> map) {
Optional<Entry<K, V>> 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) {