TreeSet with default constructor will sort the element in natural ascending order, but if you want some custom sorting according to your requirement then you should go for the Comparator interface.
eq
This is your default class Employee and you want to sort this class according to salary then.
public class Employee {
private int Id;
private String name;
private int salary;
public Employee(int id, String name, int salary) {
super();
Id = id;
this.name = name;
this.salary = salary;
}
public int getId() {
return Id;
}
public void setId(int id) {
Id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
public String toString() {
return "ID : "+Id +" Name : "+name+" Salary : "+salary+"\n";
}
}
Here we have created another class by implementing Comparator.
public class EmpSalaryComparator implements Comparator{
public int compare(Object o1, Object o2) {
Employee e1=(Employee) o1;
Employee e2=(Employee) o2;
return e1.getSalary()-e2.getSalary();
}
}
public class Test1 {
public static void main(String[] args) {
TreeSet t1=new TreeSet(new EmpSalaryComparator());
Employee e1=new Employee(1001, "Ram", 1000);
Employee e2=new Employee(1002, "lucky", 7000);
Employee e3=new Employee(1003, "sumo", 3000);
Employee e4=new Employee(1004, "kharvi", 3000);
Employee e5=new Employee(1005, "priya", 1000);
t1.add(e1);
t1.add(e2);
t1.add(e3);
t1.add(e4);
t1.add(e5);
System.out.println(t1);
}
}