What do you want (will) be possible with Java 8:
Map<String,Double> map… String maxKey=Collections.max(map.keySet(), (x,y)->Double.compare(map.get(x),map.get(y)));
or even shorter
String maxKey = Collections.max(map.keySet(), Comparator.comparingDouble(map::get));
For a previous version of Java, you should use:
String maxKey=Collections.max(map.keySet(), new Comparator<String>(){ public int compare(String x, String y) { return Double.compare(map.get(x),map.get(y)); } });
Problems with map without being final can be circumvented by assigning it a final variable right before the call:
final Map<String,Double> fmap=map; String maxKey=Collections.max(map.keySet(), new Comparator<String>(){ public int compare(String x, String y) { return Double.compare(fmap.get(x),fmap.get(y)); } });
But I think that the following helper method will be even simpler and more efficient, since it does not require any hash requests:
static <K,V extends Comparable<V>> K keyForHighestValue(Map<K,V> map) { V maxValue=Collections.max(map.values()); for(Map.Entry<K,V> e:map.entrySet()) { if(e.getValue()==maxValue) return e.getKey(); } throw new ConcurrentModificationException(); }
Holger
source share