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

TreeSet is sorted by natural order of elements.
In program 1 we used elements of Integer type, Integer class implements Comparable interface and overrides its compareTo() method.
But, for using Employee as elements 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 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.Set;
import java.util.TreeSet;
class Employee implements Comparable<Employee>{
   String name;
   String id;
   public Employee(String name, String id) { = name; = id;
   public int compareTo(Employee otherEmployee) {
      //sort Employee on basis of name(ascending order)
   public String toString() {
       return "Employee{" + "name=" + name + ", id=" + id  + '}';
* @author AnkitMittal
* Copyright (c), AnkitMittal
* 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>();
       System.out.println("treeSet : "+treeSet);

treeSet : [Employee{name=amy, id=2}, Employee{name=brad, id=1}, Employee{name=sam, id=4}]


Must read for you :