Sorting TreeMap Using Comparator
TreeMap are sorted naturally using their Keys. If you have your objects as keys then Sorting TreeMap using Comparator is a good way to decide the map order.
Lets see an example on how to use Comparator in a TreeMap
1. User Defined Object – Employee.java
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 | package com.kscodes.collections; public class Employee { private String firstName; private String lastName; private double salary; public Employee(String firstName, String lastName, double salary) { super(); this.firstName = firstName; this.lastName = lastName; this.salary = salary; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public double getSalary() { return salary; } public void setSalary(double salary) { this.salary = salary; } @Override public String toString() { return "Employee [firstName=" + firstName + ", lastName=" + lastName + ", salary=" + salary + "]"; } } |
2. Comparator – Sorting by Salary
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | package com.kscodes.collections; import java.util.Comparator; public class EmpComparator implements Comparator<Employee> { @Override public int compare(Employee o1, Employee o2) { if (o1.getSalary() > o2.getSalary()) { return 1; } else if (o1.getSalary() < o2.getSalary()) { return -1; } else { return 0; } } } |
3. Code to use Comparator
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 | package com.kscodes.collections; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.Map.Entry; public class TreeMapComparatorExample { public static void main(String args[]) { TreeMap<Employee, String> empTreeMap = new TreeMap<>(new EmpComparator()); empTreeMap.put(new Employee("Steve", "Smith", 2500), "0001"); empTreeMap.put(new Employee("John", "Doe", 1500), "0002"); empTreeMap.put(new Employee("Alex", "Rock", 4500), "0003"); empTreeMap.put(new Employee("Tim", "Bax", 1000), "0004"); Set<Entry<Employee, String>> set = empTreeMap.entrySet(); Iterator<Entry<Employee, String>> iterator = set.iterator(); while (iterator.hasNext()) { Map.Entry mapEntry = (Map.Entry) iterator.next(); System.out.print((Employee) mapEntry.getKey() + " : " + mapEntry.getValue()); System.out.println(""); } } } |
Output
After executing the above code, we get the following into the console. You can see that the TreeMap was sorted based on the employee salary