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) { = name; = id;
   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>(new Comparator<Employee>() {
                 public int compare(Employee o1, Employee o2) {
       System.out.println("treeSet : "+treeSet);
treeSet : [Employee{name=amy, id=2}, Employee{name=brad, id=1}, Employee{name=sam, id=4}]

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...
//start paginationJs //end paginationJs