This example shows how to sort LinkedHashMap by keys in Java. This example also shows how to sort LinkedHashMap using the TreeMap and a custom Comparator.
How to sort LinkedHashMap by key in Java?
The LinkedHashMap entries can be sorted by keys using the TreeMap class. The TreeMap automatically inserts the entries sorted by the key.
To do that, we will convert the LinkedHashMap to a TreeMap object using the TreeMap constructor that accepts a Map argument as given below.
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 |
import java.util.LinkedHashMap; import java.util.Map; import java.util.TreeMap; public class SortLinkedHashMapByKeysExample { public static void main(String[] args) { LinkedHashMap<Integer, String> lhmap = new LinkedHashMap<Integer, String>(); lhmap.put(1, "One"); lhmap.put(3, "Three"); lhmap.put(7, "Seven"); lhmap.put(2, "Two"); lhmap.put(5, "Five"); lhmap.put(4, "Four"); lhmap.put(6, "Six"); System.out.println("Unsorted LinkedHashMap:"); for( Map.Entry<Integer, String> entry : lhmap.entrySet() ){ System.out.println( entry.getKey() + "=>" + entry.getValue() ); } /* * To sort the LinkedHashMap by keys, * convert it to a TreeMap using the * constructor. * * TreeMap automatically sorts the entries by keys */ TreeMap<Integer, String> treeMap = new TreeMap<Integer, String>( lhmap ); System.out.println("\nSorted By Keys:"); for( Map.Entry<Integer, String> entry : treeMap.entrySet() ){ System.out.println( entry.getKey() + "=>" + entry.getValue() ); } /* * If you want the sorted entries in the LinkedHashMap, * clear it first and then add all TreeMap entries back * to the LinkedHashMap */ lhmap.clear(); lhmap.putAll(treeMap); } } |
Output
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
Unsorted LinkedHashMap: 1=>One 3=>Three 7=>Seven 2=>Two 5=>Five 4=>Four 6=>Six Sorted By Keys: 1=>One 2=>Two 3=>Three 4=>Four 5=>Five 6=>Six 7=>Seven |
If you do not want the sorted entries back in the original LinkedHashMap object, you do not need to clear it and add all sorted entries back to the LinkedHashMap object.
How to sort LinkedHashMap having custom class objects as keys?
Let’s try to sort a linked hash map having custom class objects as keys using the same approach.
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 |
import java.util.LinkedHashMap; import java.util.Map; import java.util.TreeMap; class Student{ private Integer id; private String name; public Student(Integer id, String name){ this.id = id; this.name = name; } public String toString(){ return "[" + this.id + "=>" + this.name + "]"; } } public class SortLinkedHashMapByKeysExample { public static void main(String[] args) { LinkedHashMap<Student, Integer> lhmap = new LinkedHashMap<Student, Integer>(); lhmap.put(new Student(1, "Jack"), 1); lhmap.put(new Student(5, "Emily"), 5); lhmap.put(new Student(3, "John"), 3); lhmap.put(new Student(2, "Roy"), 2); lhmap.put(new Student(4, "Maria"), 4); TreeMap<Student, Integer> treeMap = new TreeMap<Student, Integer>( lhmap ); System.out.println("Sorted By Keys:"); for( Map.Entry<Student, Integer> entry : treeMap.entrySet() ){ System.out.println( entry.getKey() + "=>" + entry.getValue() ); } } } |
Output
1 2 3 4 5 6 7 |
Exception in thread "main" java.lang.ClassCastException: com.javacodeexamples.collections.linkedhashmap.Student cannot be cast to java.lang.Comparable at java.util.TreeMap.compare(Unknown Source) at java.util.TreeMap.put(Unknown Source) at java.util.AbstractMap.putAll(Unknown Source) at java.util.TreeMap.putAll(Unknown Source) at java.util.TreeMap.<init>(Unknown Source) at com.javacodeexamples.collections.linkedhashmap.SortLinkedHashMapByKeysExample.main(SortLinkedHashMapByKeysExample.java:34) |
As you can see from the output above, the TreeMap throws a ClassCastException exception.
If the LinkedHashMap keys are objects of a custom class, then the custom class must implement the Comparable interface and define the compareTo
method or a custom Comparator object must be specified in the TreeMap constructor.
LinkedHashMap sort by keys using the Comparable interface
Let’s implement the Comparable interface in our Student class and define the compareTo
method.
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 |
import java.util.LinkedHashMap; import java.util.Map; import java.util.TreeMap; /* * 1. Implement Comparable interface in your custom * class used as a LikedHashMap key */ class Student implements Comparable<Student>{ private Integer id; private String name; public Student(Integer id, String name){ this.id = id; this.name = name; } /* * 2. Define this method in your custom class * used as a key of the LinkedHashMap */ public int compareTo(Student anotherStudent) { return this.getId() - anotherStudent.getId(); } public Integer getId(){ return this.id; } public String toString(){ return "[" + this.id + "=>" + this.name + "]"; } } public class SortLinkedHashMapByKeysExample { public static void main(String[] args) { LinkedHashMap<Student, Integer> lhmap = new LinkedHashMap<Student, Integer>(); lhmap.put(new Student(1, "Jack"), 1); lhmap.put(new Student(5, "Emily"), 5); lhmap.put(new Student(3, "John"), 3); lhmap.put(new Student(2, "Roy"), 2); lhmap.put(new Student(4, "Maria"), 4); TreeMap<Student, Integer> treeMap = new TreeMap<Student, Integer>( lhmap ); System.out.println("Sorted By Keys:"); for( Map.Entry<Student, Integer> entry : treeMap.entrySet() ){ System.out.println( entry.getKey() + "=>" + entry.getValue() ); } } } |
Output
1 2 3 4 5 6 |
Sorted By Keys: [1=>Jack]=>1 [2=>Roy]=>2 [3=>John]=>3 [4=>Maria]=>4 [5=>Emily]=>5 |
As you can see from the output, the LinkedHashMap keys are sorted by the Student class in ascending order. If you want to sort the keys in descending order, replace the compareTo
method in the above code with the code given below.
1 2 3 |
public int compareTo(Student anotherStudent) { return anotherStudent.getId() - this.getId(); } |
Output
1 2 3 4 5 6 |
Sorted By Keys: [5=>Emily]=>5 [4=>Maria]=>4 [3=>John]=>3 [2=>Roy]=>2 [1=>Jack]=>1 |
LinkedHashMap sort by keys using the Comparator interface
Another option is to create a custom Comparator and pass the object of that to the TreeMap constructor as given below.
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 63 64 65 66 67 68 69 70 71 72 73 74 75 76 |
import java.util.Comparator; import java.util.LinkedHashMap; import java.util.Map; import java.util.TreeMap; class Student{ private Integer id; private String name; public Student(Integer id, String name){ this.id = id; this.name = name; } public Integer getId(){ return this.id; } public String toString(){ return "[" + this.id + "=>" + this.name + "]"; } } class StudentComparator implements Comparator<Student>{ public int compare(Student student1, Student student2) { return student1.getId() - student2.getId(); } } class StudentDescendingComparator implements Comparator<Student>{ public int compare(Student student1, Student student2) { return student2.getId() - student1.getId(); } } public class SortLinkedHashMapByKeysExample { public static void main(String[] args) { LinkedHashMap<Student, Integer> lhmap = new LinkedHashMap<Student, Integer>(); lhmap.put(new Student(1, "Jack"), 1); lhmap.put(new Student(5, "Emily"), 5); lhmap.put(new Student(3, "John"), 3); lhmap.put(new Student(2, "Roy"), 2); lhmap.put(new Student(4, "Maria"), 4); //specify the comparator TreeMap<Student, Integer> treeMap = new TreeMap<Student, Integer>( new StudentComparator() ); //add all entries of the LinkedHashMap to TreeMap treeMap.putAll(lhmap); System.out.println("Sorted By Keys in ascending order:"); for( Map.Entry<Student, Integer> entry : treeMap.entrySet() ){ System.out.println( entry.getKey() + "=>" + entry.getValue() ); } //specify the descending comparator TreeMap<Student, Integer> treeMapDescending = new TreeMap<Student, Integer>( new StudentDescendingComparator() ); //add all entries of the LinkedHashMap to TreeMap treeMapDescending.putAll(lhmap); System.out.println("\nSorted By Keys in descending order:"); for( Map.Entry<Student, Integer> entry : treeMapDescending.entrySet() ){ System.out.println( entry.getKey() + "=>" + entry.getValue() ); } } } |
Output
1 2 3 4 5 6 7 8 9 10 11 12 13 |
Sorted By Keys in ascending order: [1=>Jack]=>1 [2=>Roy]=>2 [3=>John]=>3 [4=>Maria]=>4 [5=>Emily]=>5 Sorted By Keys in descending order: [5=>Emily]=>5 [4=>Maria]=>4 [3=>John]=>3 [2=>Roy]=>2 [1=>Jack]=>1 |
This example is a part of the LinkedHashMap in Java Tutorial.
Please let me know your views in the comments section below.
References:
Java 8 LinkedHashMap