Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting HashMaps by value

Tags:

java

hashmap

When I need to sort a HashMap by value, the advice seems to be to create the HashMap and then put the data into a TreeMap which is sorted by value.

For example: Sort a Map<Key, Value> by values (Java)

My question: why is it necessary to do this? Why not create a TreeMap(which is sorted by keys) and then sort it in place by value?

like image 555
Tom Kealy Avatar asked Feb 09 '26 23:02

Tom Kealy


1 Answers

If you know your values to be unique, you can use Guava's BiMap (bidirectional map) to store the data. Create a HashBiMap as you would your HashMap, then create a new TreeMap from its inverse:

new TreeMap<>(biMap.inverse());

That map will then be sorted by the values. Remember that what you're thinking of as "keys" and "values" will be swapped.

If your values are not unique, you can create a multimap of the inverse. A multimap is essentially a mapping from each key to one or more values. It's usually implemented by making a map from a key to a list. You don't have to do that though, because Google did it for you. Just create a multimap from your existing map, and ask Guava to invert it for you into a TreeMultimap, which, as you can guess, is a TreeMap that can hold multiple values per key.

Multimaps.invertFrom(Multimaps.forMap(myMap), new TreeMultimap<V, K>());

Multimap documentation is provided.

like image 52
Samir Talwar Avatar answered Feb 12 '26 14:02

Samir Talwar