Originally posted by Alok Pota: I would like to sort the values of a map and retain the key-value relation in doing so, is there a good way to do this?
To amplify Jim's point a bit: a Map, like a Collection, is fundamentally unsorted. You cannot sort it, anymore than you can sort a Collection, without turning it into something else first. A SortedMap is not going to help you in general, as it sorts the keys, not the values. However, if you are sure that the values in your Map are unique, you can use an inverse SortedMap mapping values to keys. If you're interested in just a sorted list of values, you could use
Finally, if your values are not guaranteed to be unique, but you still want to be able to access the key for a given value, you would have to use something like
assuming the values you put in your map are indeed Comparable; the code is easy to modify if this is not the case. - Peter
Peter den Haan | peterdenhaan.com | quantum computing specialist, Objectivity Ltd
Good points, Peter. I didn't look closely enough at the original question - I assumed that Alok wanted to sort the Map by key, not by value. It seems very unlikely to me that it would even be useful to sort a Map by value - it seems to imply that the Map should have been set up with the values and keys reversed. Alok, it sounds like you're still working on the bi-directional map you asked us about here. Are you using two HashMaps, or one big one? Either way, it should be sufficient to sort by key, rather than value. Unless I'm missing something, which of course is always possible.
What I've done in the past for this sort of thing is make a small convenience class with a key and a value, which implements Comparable and uses the value for comparisons:
Then extract the keys and values into a java.util.List of these objects, and sort that.
This approach works well if the map is either small or large but mostly static or you only need the sorted values occasionally. You probably don't want to be doing this on every "get", for example - a dual map would probably be a better choice in this case.