HashMap in Java is an unordered key-value mappings collection. To sort it, you can try using the following ways

  • Sort the HashMap's keys by using TreeMap

  • Sort the HashMap's keys or values by using TreeSet or ArrayList

Let's define two object classes (one implements Comparable interface and one doesn't) and implement some unit test classes to see the examples in practice



The above compareTo method provides the default / natural order in ascending to ComparableBook objects. If you want the default order in descending, try below

@Override
public int compareTo(ComparableBook o) {  
    return o.title.compareTo(this.title);
}

Using TreeMap, O(nlogn) time

  • Sort the HashMap's keys by creating a new TreeMap with the constructor TreeMap(Map) to copy all mappings from the specified map you want to sort

  • All keys inserted into the new TreeMap must implement the Comparable interface

    They also must be mutually comparable: k1.compareTo(k2) must not throw a ClassCastException for any keys k1 and k2 in the map


Using TreeSet, O(nlogn) time

  • Sort the HashMap's keys or values by creating a new TreeSet with the constructor TreeSet(Collection) to copy all elements from the specified collection you want to sort

  • All elements inserted into the set must implement the Comparable interface

    They also must be mutually comparable: : e1.compareTo(e2) must not throw a ClassCastException for any elements in the set

  • When HashMap's values are duplicate, try using ArrayList to sort


Using ArrayList, O(nlogn) time

  • Sort the HashMap's keys or values by creating a new ArrayList with the constructor ArrayList(Collection) to copy all elements from the specified collection you want to sort

  • Using Collections.sort(List) to sort Comparable implemented keys or values

  • Using Collections.sort(List, Comparator) to control over the sort order or to provide natural ordering to non-Comparable implemented keys or values