Java. Sorted map by value

user1711160 picture user1711160 · Nov 22, 2012 · Viewed 8.6k times · Source

Possible Duplicate:
How to sort a Map<Key, Value> on the values in Java?

I need sorted map like TreeMap but sorted by value. My map will be huge, so i can't just sort my map anytime i need. Exist any good solution to resolve this problem? Maybe exist external jar who meets this?

Answer

Mark A. Fitzgerald picture Mark A. Fitzgerald · Nov 22, 2012

There are a number of ways to satisfy your requirement. As you have subsequently clarified that you may have duplicate objects in your current TreeMap, perhaps you could replace your TreeMap with a third-party multimap (Guava, Apache Commons Collections), then swap your keys and values around - i.e. replace TreeMap<Key, Value> with Multimap<Value, Key>. Depending on the details of your situation I believe this stands a good chance of working for you.