I have a TreeMap
like so:
{
"one": "First option",
"two": "Second option",
"three": "Third option",
"four": "Last option"
}
I want to resort this object so that the output is like this:
{
"four": "First option",
"three": "Second option",
"two": "Third option",
"one": "Last option"
}
I was looking at some of the commons collections utilities from apache, but did not see anything immediately that would do the trick.
What is the cleanest way to write this without a bunch of loops?
I think that you can only use a LinkedHashMap to store such a list, because it is not in alphabetical order. But LinkedHashMap keeps the order in which the elements have been added, so would be fine.
I do not think anything can be done much simpler than putting all map entries (obtainable via entrySet() method) into ArrayList and then adding them to another map in the reverse order, by iterating through this array. If it would be reverse iterators, we could derive a class that swaps them, but looks like there are no iterators that would move in reverse order, so overriding is not an option.
Changing the hash code of the keys after the map is created will not change the order because the buckets are already there. It, however, likely will prevent the map from working properly.