Java sort HashMap by key example shows how to sort HashMap by key in Java using the TreeMap class and a Comparator.
How to Sort HashMap by Key in Java?
The HashMap is meant for quick look-ups and may not maintain the order of the inserted elements. However, retrieving the values based on sorted keys is possible in below given ways.
Using TreeMap
If you have a requirement to access the HashMap values by the sorted keys, you should use the TreeMap class instead. If you already have a HashMap object, you can convert the HashMap to a TreeMap object, thus sorting it by the keys automatically as given in the below example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
package com.javacodeexamples.basic.sorting; import java.util.HashMap; import java.util.TreeMap; public class SortHashMapByKeysExample { public static void main(String[] args) { //create a new HashMap HashMap<Integer, String> hMapNumbers = new HashMap<Integer, String>(); hMapNumbers.put(new Integer(2), "Two"); hMapNumbers.put(new Integer(1), "One"); hMapNumbers.put(new Integer(3), "Three"); hMapNumbers.put(new Integer(4), "Four"); /* * print HashMap keys, output might be * different for you as HashMap may not maintain * order. */ System.out.println("HashMap contains..."); for(Integer key : hMapNumbers.keySet()){ System.out.println("Key: " + key + ", Value: " + hMapNumbers.get(key)); } System.out.println(""); /* * To sort HashMap by keys, simply use TreeMap's * constructor which accepts a Map */ //convert HashMap to TreeMap TreeMap<Integer, String> treeMapNumbers = new TreeMap<Integer, String>(hMapNumbers); //print TreeMap which is sorted by keys System.out.println("TreeMap contains..."); for(Integer key : treeMapNumbers.keySet()){ System.out.println("Key: " + key + ", Value: " + treeMapNumbers.get(key)); } } } |
Output
1 2 3 4 5 6 7 8 9 10 11 |
HashMap contains... Key: 4, Value: Four Key: 2, Value: Two Key: 1, Value: One Key: 3, Value: Three TreeMap contains... Key: 1, Value: One Key: 2, Value: Two Key: 3, Value: Three Key: 4, Value: Four |
Now let’s try to put custom class objects as the key instead of Integer objects. We are going to store the employee and manager relation mappings using the Employee class objects in the below given example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
package com.javacodeexamples.basic.sorting; import java.util.HashMap; import java.util.TreeMap; import com.javacodeexamples.common.Employee; public class SortHashMapByKeysExample { public static void main(String[] args) { //HashMap containing employee and it's manager mappings HashMap<Employee, Employee> hMapEmployeeManager = new HashMap<Employee, Employee>(); hMapEmployeeManager.put(new Employee("021", "Emp1", "IT"), new Employee("0033", "Manager1", "IT")); hMapEmployeeManager.put(new Employee("005", "Emp1", "IT"), new Employee("0033", "Manager1", "IT")); hMapEmployeeManager.put(new Employee("004", "Emp1", "IT"), new Employee("0033", "Manager1", "IT")); hMapEmployeeManager.put(new Employee("011", "Emp1", "IT"), new Employee("0033", "Manager1", "IT")); //print HashMap System.out.println("Unsorted HashMap Keys & Values"); for(Employee e : hMapEmployeeManager.keySet()){ System.out.println("Employee: " + e + ", Manager: " + hMapEmployeeManager.get(e)); } //convert HashMap to TreeMap, thus sorting it TreeMap<Employee, Employee> treeMapEmployees = new TreeMap<Employee, Employee>(hMapEmployeeManager); //print TreeMap System.out.println("Sorted TreeMap Keys & Values"); for(Employee e : treeMapEmployees.keySet()){ System.out.println("Employee: " + e + ", Manager: " + treeMapEmployees.get(e)); } } } |
Output
1 2 3 4 5 6 7 8 9 10 11 12 |
Unsorted HashMap Keys & Values Employee: [005 : Emp1 : IT], Manager: [0033 : Manager1 : IT] Employee: [004 : Emp1 : IT], Manager: [0033 : Manager1 : IT] Employee: [011 : Emp1 : IT], Manager: [0033 : Manager1 : IT] Employee: [021 : Emp1 : IT], Manager: [0033 : Manager1 : IT] Exception in thread "main" java.lang.ClassCastException: com.javacodeexamples.common.Employee cannot be cast to java.lang.Comparable at java.util.TreeMap.compare(TreeMap.java:1188) at java.util.TreeMap.put(TreeMap.java:531) at java.util.AbstractMap.putAll(AbstractMap.java:273) at java.util.TreeMap.putAll(TreeMap.java:322) at java.util.TreeMap.<init>(TreeMap.java:180) at com.javacodeexamples.basic.sorting.SortHashMapByKeysExample.main(SortHashMapByKeysExample.java:40) |
Well, we encountered the ClassCastException
exception. What went wrong? The first example worked because we used Integer objects as keys and Integer class implements the Comparable interface (so that Integer objects can be compared to one another while being sorted).
If you want to use your custom class objects as key, either the class needs to implement the Comparable interface or you need to provide a custom comparator before the object can be sorted by the TreeMap.
Below given example uses a custom Comparator to compare Employee objects and sorts them based on the employee name.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
package com.javacodeexamples.basic.sorting; import java.util.Comparator; import java.util.HashMap; import java.util.TreeMap; import com.javacodeexamples.common.Employee; public class SortHashMapByKeysExample { public static void main(String[] args) { //HashMap containing employee and it's manager mappings HashMap<Employee, Employee> hMapEmployeeManager = new HashMap<Employee, Employee>(); hMapEmployeeManager.put(new Employee("021", "Scott", "IT"), new Employee("0033", "Carl", "IT")); hMapEmployeeManager.put(new Employee("005", "Adam", "IT"), new Employee("0033", "Carl", "IT")); hMapEmployeeManager.put(new Employee("004", "Raj", "IT"), new Employee("0033", "Carl", "IT")); hMapEmployeeManager.put(new Employee("011", "Marie", "IT"), new Employee("0033", "Carl", "IT")); //print HashMap System.out.println("Unsorted HashMap Keys & Values"); for(Employee e : hMapEmployeeManager.keySet()){ System.out.println("Employee: " + e + ", Manager: " + hMapEmployeeManager.get(e)); } System.out.println(""); //Create a new TreeMap with the custom Comparator TreeMap<Employee, Employee> treeMapEmployees = new TreeMap<Employee, Employee>(new EmpComparator()); //put all elements of HashMap to TreeMap, thus sorting them treeMapEmployees.putAll(hMapEmployeeManager); //print TreeMap System.out.println("Sorted TreeMap Keys & Values"); for(Employee e : treeMapEmployees.keySet()){ System.out.println("Employee: " + e + ", Manager: " + treeMapEmployees.get(e)); } } } class EmpComparator implements Comparator<Employee>{ public int compare(Employee e1, Employee e2) { return e1.getName().compareToIgnoreCase(e2.getName()); } } |
Output
1 2 3 4 5 6 7 8 9 10 11 |
Unsorted HashMap Keys & Values Employee: [005 : Adam : IT], Manager: [0033 : Carl : IT] Employee: [004 : Raj : IT], Manager: [0033 : Carl : IT] Employee: [021 : Scott : IT], Manager: [0033 : Carl : IT] Employee: [011 : Marie : IT], Manager: [0033 : Carl : IT] Sorted TreeMap Keys & Values Employee: [005 : Adam : IT], Manager: [0033 : Carl : IT] Employee: [011 : Marie : IT], Manager: [0033 : Carl : IT] Employee: [004 : Raj : IT], Manager: [0033 : Carl : IT] Employee: [021 : Scott : IT], Manager: [0033 : Carl : IT] |
Finally, you can change below given line,
1 2 3 |
//Create a new TreeMap with the custom Comparator TreeMap<Employee, Employee> treeMapEmployees = new TreeMap<Employee, Employee>(new EmpComparator()); |
to this line,
1 2 3 4 5 6 7 |
//Create a new TreeMap with the custom Comparator TreeMap<Employee, Employee> treeMapEmployees = new TreeMap<Employee, Employee>(new Comparator<Employee>(){ public int compare(Employee e1, Employee e2) { return e1.getName().compareToIgnoreCase(e2.getName()); } }); |
and remove the the EmpComparator class definition to use an anonymous Comparator.
Please also check out How to sort HashMap by values example.
This example is a part of the Java HashMap tutorial.
Please let me know your views in the comments section below.