HashMap is not meant to keep entries in sorted order, but if you have to sort HashMap based upon keys or values, you can do that in Java. Sorting HashMap on keys is quite easy, all you need to do is to create a TreeMap by copying entries from HashMap. TreeMap is an implementation of
SortedMap and keeps keys in their natural order or a custom order specified by Comparator provided while creating TreeMap. This means you can process entries of HashMap in a sorted order but you cannot pass a HashMap containing mappings in a specific order, this is just not possible because
HashMap doesn't guarantee any ordering. On other hand, sorting HashMap by values is rather complex because there is no direct method to support that operation. You need to write code for that. In order to sort HashMap by values you can first create a Comparator, which can compare two entries based on values. Then get the Set of entries from Map, convert Set to List and use
Collections.sort(List) method to sort your list of entries by values by passing your customized value comparator. This is similar of
how you sort an ArrayList in Java. Half of the job is done by now. Now create a new
LinkedHashMap and add sorted entries into that. Since
LinkedHashMap guarantees insertion order of mappings, you will finally have a Map where contents are sorted by values.