.
This commit is contained in:
parent
1ad0c04839
commit
5eab831bb5
@ -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 <K, V extends Comparable<V>> V maxUsingCollectionsMax(Map<K, V> map) {
|
||||
|
||||
Entry<K, V> maxEntry = Collections.max(map.entrySet(), Entry.comparingByValue());
|
||||
|
||||
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());
|
||||
}
|
||||
});
|
||||
return maxEntry.getValue();
|
||||
}
|
||||
|
||||
public <K, V extends Comparable<V>> V maxUsingCollectionsMaxAndLambda(Map<K, V> map) {
|
||||
|
||||
Entry<K, V> maxEntry = Collections.max(map.entrySet(), Entry.comparingByValue());
|
||||
|
||||
Entry<K, V> maxEntry = Collections.max(map.entrySet(), (Entry<K, V> e1, Entry<K, V> e2) -> e1.getValue()
|
||||
.compareTo(e2.getValue()));
|
||||
return maxEntry.getValue();
|
||||
}
|
||||
|
||||
public <K, V extends Comparable<V>> V maxUsingCollectionsMaxAndMethodReference(Map<K, V> map) {
|
||||
|
||||
Entry<K, V> maxEntry = Collections.max(map.entrySet(), Entry.comparingByValue());
|
||||
Entry<K, V> maxEntry = Collections.max(map.entrySet(), Comparator.comparing(Map.Entry::getValue));
|
||||
|
||||
return maxEntry.getValue();
|
||||
}
|
||||
|
||||
public <K, V extends Comparable<V>> V maxUsingStreamAndLambda(Map<K, V> map) {
|
||||
|
||||
Optional<Entry<K, V>> maxEntry = map.entrySet()
|
||||
.stream()
|
||||
.max(Entry.comparingByValue());
|
||||
.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(Entry.comparingByValue());
|
||||
|
||||
.max(Comparator.comparing(Map.Entry::getValue));
|
||||
return maxEntry.get()
|
||||
.getValue();
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
Map<Integer, Integer> map = new HashMap<>();
|
||||
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
|
||||
|
||||
map.put(1, 3);
|
||||
map.put(2, 4);
|
||||
|
Loading…
x
Reference in New Issue
Block a user