Program to Sort Set in Ascending order by using TreeSet and implementing Comparator interface, where elements are customObject/Employee type.







In previous program, Employee implemented Comparable but in this program TreeSet will implement comparator interface.
Comparator interface has been used in form of anonymous inner class.


Note : If we Employee don’t implement Comparable interface neither Treeset implement Comparator interface than ClassCastException (RunTimeException) will be thrown. Because, internally TreeSet uses TreeMap for storing elements and TreeMap calls compare method for comparing elements, while comparing elements casting to java.lang.Comparable will fail at runtime.

import java.util.Comparator;
import java.util.Set;
import java.util.TreeSet;
class Employee{
   String name;
   String id;
   public Employee(String name, String id) {
       this.name = name;
       this.id = id;
   }
   @Override
   public String toString() {
       return "Employee{" + "name=" + name + ", id=" + id  + '}';
   }
}
/**
* @author AnkitMittal
* Copyright (c), AnkitMittal JavaMadeSoEasy.com
* Main class
*/
public class SortSet {
   public static void main(String...a){
       Employee emp1=new Employee("sam","4");
       Employee emp2=new Employee("amy","2");
       Employee emp3=new Employee("brad","1");
      Set<Employee> treeSet = new TreeSet<Employee>(new Comparator<Employee>() {
                 @Override
                 public int compare(Employee o1, Employee o2) {
                       return o1.name.compareTo(o2.name);
                 }
          });
       treeSet.add(emp1);
       treeSet.add(emp2);
       treeSet.add(emp3);
       System.out.println("treeSet : "+treeSet);
      
   }
}
/*OUTPUT
treeSet : [Employee{name=amy, id=2}, Employee{name=brad, id=1}, Employee{name=sam, id=4}]
*/


eEdit
Must read for you :