Another way to achieve this by only processing the elements once could be to use an appropriate collector:
Entry<Integer, Set<String>> highestKey = map.entrySet().stream()
.collect(groupingBy(Entry::getValue, TreeMap::new, mapping(Entry::getKey, toSet())))
.lastEntry();
Set<String> result = highestKey != null ? highestKey.getValue() : Set.of();
Here we stream()
over the entries in the map. By grouping by the value of the entries we can collect into a new map. By stating that it should collect into a TreeMap
, it will be sorted according to it's keys. By doing this, we can get the highest value by using lastEntry()
.
mapping()
is used to make sure we get the keys of the original map as the value in the new map, whithout this we would get the entries as values.
Finally, the last null check is needed in case of an empty map, because there won't be any last entry.
A fully working example including imports:
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
import static java.util.stream.Collectors.*;
class Sorting {
public static void main(String[] args) {
Map<String, Integer> map = Map.of(
"name1", 3,
"name2", 14,
"name3", 4,
"name4", 14,
"name5", 2,
"name6", 6);
Entry<Integer, Set<String>> highestKey = map.entrySet().stream()
.collect(groupingBy(Entry::getValue, TreeMap::new, mapping(Entry::getKey, toSet())))
.lastEntry();
Set<String> result = highestKey != null ? highestKey.getValue() : Set.of();
}
}