Program to Sort Map by key in Ascending order by using TreeMap and implementing Comparable interface, where key is customObject/Employee type







TreeMap is sorted by natural order of keys.
In program 3 we used Integer as key, Integer class implements Comparable interface and overrides its compareTo() method.
But, for using Employee as key we it must implement Comparable interface and override its compareTo() method.




Note : If we Employee don’t implement Comparable interface and override its compareTo() method than ClassCastException (RunTimeException) will be thrown. Because, internally TreeMap calls compare method for comparing keys , while comparing keys casting to java.lang.Comparable will fail at runtime.

import java.util.Map;
import java.util.TreeMap;
class Employee implements Comparable<Employee>{
   String name;
   String id;
   public Employee(String name, String id) {
       this.name = name;
       this.id = id;
   }
  
   @Override
   public int compareTo(Employee otherEmployee) {
      //sort Employee on basis of name(ascending order)
      return this.name.compareTo(otherEmployee.name);
   }
   @Override
   public String toString() {
       return "Employee{" + "name=" + name + ", id=" + id  + '}';
   }
}
/**
* @author AnkitMittal
* Copyright (c), AnkitMittal JavaMadeSoEasy.com
* Main class
*/
public class SortMapByKeyAscending {
   public static void main(String...a){
       Employee emp1=new Employee("sam","4");
       Employee emp2=new Employee("amy","2");
       Employee emp3=new Employee("brad","1");
       Map<Employee, Integer> treeMap = new TreeMap<Employee, Integer>();
       treeMap.put(emp1, 1);
       treeMap.put(emp2, 1);
       treeMap.put(emp3, 1);
       System.out.println("treeMap : "+treeMap);
      
   }
}
/*OUTPUT
treeMap : {Employee{name=amy, id=2}=1, Employee{name=brad, id=1}=1, Employee{name=sam, id=4}=1}
*/


Must read for you :
Must read for you :

No comments:

Post a Comment