So you have a Map in your Java program and you want to process its data in sorted order. Since Map doesn't guarantee any order for its keys and values, you always end up with unsorted keys and Map. If you really need a sorted Map then think about using
TreeMap, which keeps all keys in a sorted order. This could be either natural order of keys (defined by
Comparable) or a custom order (defined by
Comparator), which you can provide, while creating instance of TreeMap. If you don't have your data in a sorted Map then only option remains is to get the keys, sort them and then process data in that order. Since keys are unique in Map, it returns a Set of keys, which means you cannot sort them by using
Collections.sort() method, which accept a List. So what to do? Well, we can convert our Set into List as shown in
this example, then sort them using
sort() method in any order and process them accordingly. Now which approach is better, either using
TreeMap or keeping mappings in an unsorted general purpose Map implementation like
HashMap or Hashtable? well both have their advantages and disadvantages, but if requirement is always keep keys in sorted order then use
TreeMap, though insertions will be slow but keys will always remain in sorted order. On the other hand, if requirement is just to process data in a particular order, which also varies depending upon which method is using Map, then use general purpose Map e.g.
HashMap and only sort when needed. Insertion will be much faster, but it will require additional time to sort keys before processing. In next section, we will see example of both approach of sorting Map in Java.