Saturday, 19 April 2014

TreeSet (Comparator comparator)

public TreeSet(Comparator<? super E> comparator)
Constructs a new, empty tree set, sorted according to the specified comparator.

class Employee1{
 Integer number;
 String name;
 
 Employee1(int number, String  name){
  this.number = number;
  this.name = name;
 } 
 
 public String toString(){
  return number + " " + name;
 }
 
}


import java.util.Comparator;

class EmployeeNameComparator implements Comparator{

 public int compare(Object o1, Object o2){
  Employee1 e1 = (Employee1) o1;
  Employee1 e2 = (Employee1) o2;
  return e1.name.compareTo(e2.name);
 } 
 
}

import java.util.Comparator;
class EmployeeIdComparator implements Comparator{

 public int compare(Object o1, Object o2){
  Employee1 e1 = (Employee1) o1;
  Employee1 e2 = (Employee1) o2;
  return e1.number.compareTo(e2.number);
 }
 
}

import java.util.*;

class TreeSetConstructor3{
 public static void main(String args[]){
  TreeSet<Employee1> mySet1 = new TreeSet<> (new EmployeeNameComparator());
  TreeSet<Employee1> mySet2 = new TreeSet<> (new EmployeeIdComparator());
  
  Employee1 e1 = new Employee1(1, "Ram");
  Employee1 e2 = new Employee1(2, "Naveed");
  Employee1 e3 = new Employee1(3, "Jaideep");
  
  mySet1.add(e1);
  mySet1.add(e2);
  mySet1.add(e3);
  
  mySet2.add(e1);
  mySet2.add(e2);
  mySet2.add(e3);
  
  System.out.println("Elements in mySet1 are");
  System.out.println(mySet1);
  
  System.out.println("\nElements in mySet2 are");
  System.out.println(mySet2); 
 }
}

Output
Elements in mySet1 are
[3 Jaideep, 2 Naveed, 1 Ram]

Elements in mySet2 are
[1 Ram, 2 Naveed, 3 Jaideep]

As you observe the output mySet1 displays the elements in name order, where as mySet2 in number order.


Prevoius                                                 Next                                                 Home

No comments:

Post a Comment