Home » Core Java » How to sort HashMap by key and by value

How to sort HashMap by key and by value

Sort HashMap by Key ::
By default hashmap does not maintain order of the elements,so we can not guarantee how the elements will be printed/accessed in hashMap. For maintaining order we can use another data structure called “TreeMap” which implements “SortedMap” interface and sorts the map by key in ascending order.


Sort HashMap by Value::
To sort Hashmap by value ,we need to pass the entrire map to a list and then call Collections.sort() method to sort the list.Using Compartor class of java.util package we can override compare(object1,object2) to sort the values.
compare() method returns 1 if valueof firts object is greater than second and -1 if value of first object is less than value of second object and it returns 0 if values of first and second object are equal.

Output ::

Leave a comment

Your email address will not be published. Required fields are marked *

fourteen + 20 =