2

I have a HashMap of arbitrary objects, with Double values as the value: HashMap<MyObject, Double> myMap = new HashMap<>();. I can get the maximum Double value in the HashMap using Collections.max(myMap.values()); but I need to get the corresponding key for that value. Is there an easy way to do this with the Collections API it or would I need an iterator? I've thought about getting the position of the max value and then querying the HashMap for that position and get the key but I'm not sure how to do that.

EDIT: I can change the type from a HashMap to something else if necessary, but those two types (Object and Double) need to stay the same.

Tom Oakley
  • 6,065
  • 11
  • 44
  • 73
  • 1
    You would need an iterator. See http://stackoverflow.com/questions/5911174/finding-key-associated-with-max-value-in-a-java-map – Ram Mar 11 '16 at 11:20
  • sorry about the extra comment I've deleted it hehe :) – Ram Mar 11 '16 at 11:23
  • Why can you change from HashMap to something else? Why is it a HashMap currently? Do you really do key lookups by MyObject? – Thilo Mar 11 '16 at 11:23

2 Answers2

5

Just iterate the entry set looking for the largest value:

Map.Entry<MyObject, Double> maxEntry = null;
for (Map.Entry<MyObject, Double> entry : map.entrySet()) {
  if (maxEntry == null || entry.getValue() > maxEntry.getValue()) {
    maxEntry = entry;
  }
}
MyObject maxKey = maxEntry.getKey();  // Might NPE if map is empty.

or, if you want to get all keys with maximal value:

double maxValue = null;
List<MyObject> maxKeys = new ArrayList<>();
for (Map.Entry<MyObject, Double> entry : map.entrySet()) {
  if (maxValue == null || maxValue.equals(entry.getValue())) {
    maxValue = entry.getValue();
    maxKeys.add(entry.getKey());
  } else if (entry.getValue() > maxValue) {
    maxValue = entry.getValue();
    maxKeys.clear();
    maxKeys.add(entry.getKey());
  }
}
Andy Turner
  • 137,514
  • 11
  • 162
  • 243
  • That seems like the best way. But note that there may be more than one "maximum". Depends on the application if that is possible or important. – Thilo Mar 11 '16 at 11:22
  • thanks, this works great! I thought about using an iterator but wanted to check if it was possible with collections first. I'll accept your answer in 5 minutes when it allows me to :) – Tom Oakley Mar 11 '16 at 11:24
1

2 things here.

1) There is no way to get your key with Collections framework by giving it's value. You would need an iterator.

2) Telling the same, keys are unique and not values. You have to handle the case of duplicated values.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
  • Hey, thanks for explaining why I ca't do it with the collections framework - makes sense. I accepted Andy's answer though as he had the code ready. – Tom Oakley Mar 11 '16 at 11:26
  • @TomOakley That is what my point. you/answerer need to write the code. Collections framework don't have readymade code to use it. – Suresh Atta Mar 11 '16 at 11:27