How to sort HashMap in Java by Keys ?

In this article we will see. How we can sort a HashMap by Keys and Values. Sorting by keys is very straight forward. We just need to create a TreeMap from the HashMap. The TreeMap is a Red-Black tree based NavigableMap implementation. The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used. The Comparator is only required when we are Storing our custom Object [like an Employee, Student..] as a key in the TreeMap. Consider the following examples where we are sorting a HashMap by its keys using a TreeMap.

When the HashMap has Simple Keys:

To create a TreeMap from the HashMap we just need to pass the HashMap in TreeMap’s constructor.

import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

public class SortMapExample {

    public static void main(String[] args) {

        Map studentMap = new HashMap<>();
        studentMap.put(10, "Jackson Bird");
        studentMap.put(2, "Damon Fennimore");
        studentMap.put(23, "Edmond Meskill");
        studentMap.put(35, "Lionel Presley");

        System.out.println("Printing the unsorted Map >> ");
        studentMap.forEach((k, v) ->
                System.out.println("Id : " + k + " Name : " + v));

        System.out.println("-----------------------------");
        /**
         * Create a TreeMap from the HashMap to sort the Map in
         * natural order of Key
         */
        Map sortedStudentMap = new TreeMap<>(studentMap);
        System.out.println("Printing the sorted Map >> ");
        sortedStudentMap.forEach((k, v) ->
                System.out.println("Id : " + k + " Name : " + v));
    }
}

Output of the program is :

Printing the unsorted Map >> 
 Id : 2 Name : Damon Fennimore
 Id : 35 Name : Lionel Presley
 Id : 23 Name : Edmond Meskill
 Id : 10 Name : Jackson Bird

Printing the sorted Map >> 
 Id : 2 Name : Damon Fennimore
 Id : 10 Name : Jackson Bird
 Id : 23 Name : Edmond Meskill
 Id : 35 Name : Lionel Presley

When the HashMap has Composite Keys:

Here we have a Map , where the key is a Student Object and the value is List . The data structure is storing Students with their first year CGPA. If we store these Student  Objects in a TreeMap then we also need to provide the sorting logic of Student to the TreeMap . This can be archived by passing a Student Comparator to the TreeMap constructor. Following is the Student Class.

class Student {
	
  Integer studentId;
  String name;

  public Student(int id, String n) {
	studentId = id;
	name = n;
  }

  @Override
  public String toString() {
	return "Student [studentId=" + studentId + ", name=" + name + "]";
  }
}

The Comparator we need to provide to the TreeMap is :

class StudentComp implements Comparator{

  @Override
  public int compare(Student s1, Student s2) {
	return s1.studentId.compareTo(s2.studentId);
  }
}

Now check the Program where we are sorting the Students using a TreeMap:

public class SortMapExample {

    public static void main(String[] args) {

        Map<Student, List<Double>> studentMap = new HashMap<>();
        studentMap.put(new Student(10, "Jackson Bird"), Arrays.asList(7.8D, 8.2D));
        studentMap.put(new Student(5, "Damon Fennimore"), Arrays.asList(8.8D, 9.2D));
        studentMap.put(new Student(12, "Edmond Meskill"), Arrays.asList(6.8D, 8.2D));
        studentMap.put(new Student(1, "Lionel Presley"), Arrays.asList(6.8D, 9.29D));

        System.out.println("Printing the unsorted Map >> ");
        studentMap.forEach((k, v) ->
                System.out.println("Id : " + k + " CGPA : " + v));

        System.out.println("-----------------------------");
        /**
         * Create a TreeMap from the HashMap to sort the Map in natural order of
         * Key
         */
        Map<Student, List<Double>> sortedStudentMap = new TreeMap<>(new StudentComp());
        sortedStudentMap.putAll(studentMap);
        System.out.println("Printing the unsorted Map >> ");
        sortedStudentMap.forEach((k, v) ->
                System.out.println("Id : " + k + " CGPA : " + v));
    }
}

Categories: Map

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s