Friday, 6 June 2014

TreeMap : comparator() : Get the comparator used

public Comparator<? super K> comparator()
Returns the comparator used to order the keys in this map, or null if this map uses the natural ordering of its keys.

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 EmployeeIdComparator implements Comparator<Employee1>{

 public int compare(Employee1 e1, Employee1 e2){
  return e1.number.compareTo(e2.number);
 }
 
 public String toString(){
  return "EmployeeIdComparator";
 }
}

import java.util.*;

class TreeMapComparator{
 public static void main(String args[]){
  TreeMap<Employee1, Integer> myMap;
  Comparator comparator;
  
  myMap = new TreeMap<> (new EmployeeIdComparator());
  
  /* Insert data to myMap */
  myMap.put(new Employee1(4, "Krishna"), 15000);
  myMap.put(new Employee1(2, "Anand"), 95000);
  myMap.put(new Employee1(3, "Kishore"), 50000);
  myMap.put(new Employee1(1, "Raju"), 70000);
  
  System.out.println("Elements in myMap are");
  System.out.println(myMap); 

  System.out.print("Comparator used is ");
  comparator = myMap.comparator();
  System.out.println(comparator);
 }
}

Output
Elements in myMap are
{1 Raju=70000, 2 Anand=95000, 3 Kishore=50000, 4 Krishna=15000}
Comparator used is EmployeeIdComparator


Prevoius                                                 Next                                                 Home

No comments:

Post a Comment