Is there a method (maybe with Google Collections) to obtain the min value of a Map(Key, Double)
?
In the traditional way, I would have to sort the map ac
In Java 8 we can get easily:
Double minValue = map.entrySet().stream().min(Map.Entry.comparingByValue()).get().getValue();
Double maxValue = map.entrySet().stream().max(Map.Entry.comparingByValue()).get().getValue();
I'd be inclined to use a Google Collections BiMap:
String minKey = HashBiMap.create(map).inverse().get(Collections.min(map.values()));
Or something like that (not tested).
Using java 8 (and static imports). We can make @superfav's solution much tidier:
Map<String, Double> myMap;
String theKeyWithHighestValue = Collections.min(myMap.entrySet(), comparingDouble(Entry::getValue)).getKey()
In order to do it efficiently, you may want to define your own data structure, such that it implements the Map interface,but also allows efficient getMin() operation.
This can be done using two internal data structures: a map and a tree (or heap data structure). Each time a new pair (K,V) is added, add them to the map, and also to the tree (as a single entry). This allows O(1) time for get(Key) operations, and O(log n) time for addition, removal, and getMin operations.
Java8 One-Liner
Key key = Collections.min(map.entrySet(), Map.Entry.comparingByValue()).getKey()
Using Java 8 streams:
return map
.entrySet()
.stream()
.sorted(Comparator.comparingDouble(Map.Entry::getValue))
.findFirst()
.map(Map.Entry::getValue);
Or
return map
.entrySet()
.stream()
.min(Comparator.comparingDouble(Map.Entry::getValue))
.map(Map.Entry::getValue);
But if you want to do it multiple times, then definitely give heap a look.