This is not basically how to sort the HashMap based on keys. For that I could directly use TreeMap without a wink 🙂
What I have at the moment is
Map<String, Object> favoritesMap = new HashMap<String, Object>();
and its contents can be
["Wednesdays" : "abcd"]
["Mondays" : "1234"]
["Not Categorized" : "pqrs"]
["Tuesdays" : "5678"]
I want to sort the HashMap based on keys and additional to this I need “Not Categorized” to be the last one to retrieve.
So expected while iterating over keySet is
["Mondays", "Tuesdays", "Wednesdays", "Not Categorized"] i.e. sorted on keys and "Not Categorized" is the last one
Thought of going for HashMap while creating and at the end add ["Not Categorized" : "pqrs"] but HashMap does not guarantee the order 🙂
Any other pointers for the solution?
Are you specifically excluding
TreeMapfor some external reason? If not you could obviously useTreeMapwith a specially madeComparator.Have you considered any of the other
SortedMaps?If
TreeMapis definitely out I would extendHashMapand make it look like there is always one more entry but that is certainly not a trivial piece of work. You should have a very good reason not to use aSortedMapbefore going down this road.Added
Here is an example of how you can make a particular entry always sort to the end using a
TreeMap:I wonder if you are looking for some variant of that?