Wednesday, April 20, 2016

How to use comparator in Java ??

package : java.util
public interface Comparator<T>
 
A comparison function that imposes a total ordering on some 
collection of objects.They can be passed to a sort method 
(Collections.sort()) | Arrays.sort()) to allow precise control
over the sort order. 
 
It provides multiple sorting sequence i.e. you can sort the
elements based on any data member. For instance it may be 
on rollno, name, age or anything else.  

Can also be used to control the order of certain data structures 
Sorted sets or Sorted maps , or to provide ordering of collections
of objects that do not have a natural ordering.
 
The ordering set by a comparator c on a set of elements S is said
to be consistent with equals id c.compare(s1,s2) == 0 is logically
same as s1.equals(s2) for every s1 , s2 in S.
 
If compare is not consistent with equals for a sorted set or a 
sorted map , the set or map behaves weirdly as the sorted set / map 
violates the contract set for a set or a map.

Method detail :

int compare(T o1 , T o2);

Compares two arguments for order .
-> o1 is less than o2 , returns negative 
-> o1 is equal to o2 , returns 0 
-> o1 is greater than o2 , returns positive.

The above is a signum function like sgn(expression) that returns 
-1 ,0 or 1 based on the sgn(expression) is negative , zero or 
positive.

Implementor should take care of the following : 
1. Ensure that sgn(compare(x, y)) == -sgn(compare(y, x)) 
for all x and y. 
2. Ensure that the relation is transitive: 
((compare(x, y)>0) && (compare(y, z)>0)) implies compare(x, z)>0.
3. Ensure that compare(x, y)==0 implies that 
sgn(compare(x, z))==sgn(compare(y, z)) for all z.

It is generally the case, but not strictly required that
(compare(x, y)==0) == (x.equals(y)).Generally speaking, any 
comparator that violates this condition should clearly indicate 
this fact. The recommended language is "Note: this comparator 
imposes orderings that are inconsistent with equals."

Exercise : 
 
package sample ;
public class City {
 private String name;
 private int number;

 City(String name, int number) {
  this.name = name;
  this.number = number;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public int getNumber() {
  return number;
 }

 public void setNumber(int number) {
  this.number = number;
 }
} 
 
The above is a model class City having two instance variables 
number and Name .
--------------------------------------------------------------
package sample;

import java.util.Comparator;

public class NumberComparator implements Comparator<City>{

 @Override
 public int compare(City o1, City o2) {
  return o1.getNumber() - o2.getNumber();
 }
} 
 
The above is a number comparator which implements the compare 
method and compares the city numbers .
----------------------------------------------------------------
package sample;

import java.util.Comparator;

public class NameComparator implements Comparator<City> {

 @Override
 public int compare(City o1, City o2) {
  return o1.getName().compareTo(o2.getName());
 }
}

The above is a name comparator which uses the Strings' compareTo 
method to compare the City based on the names.
----------------------------------------------------------------
For below class please see comments : 

package sample;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class TestComparator {

 public static void main(String[] args) {
  List<City> cList = new ArrayList<City>();
  cList.add(new City("Acity", 10));
  cList.add(new City("Zity", 4));
  cList.add(new City("Fcity", -5));
  cList.add(new City("Kcity", 99));
  cList.add(new City("Rcity", 3));
  cList.add(new City("Bcity", 25));
  
  System.out.println("Name Comparator"); 
                // Sorting the list by passing the nameComparator
  Collections.sort(cList, new NameComparator());
  for (City c : cList) {
   System.out
     .println("City : " + c.getNumber() + " ). " + c.getName());
  }

  System.out.println("Number Comparator");                // Sorting the list by passing the numberComparator    
  Collections.sort(cList, new NumberComparator());
  for (City c : cList) {
   System.out
     .println("City : " + c.getNumber() + " ). " + c.getName());
  }
 } 
}
 
Output : -
  
  Name Comparator
  Name : 10 ). Acity
  Name : 25 ). Bcity
  Name : -5 ). Fcity
  Name : 99 ). Kcity
  Name : 3 ). Rcity
  Name : 4 ). Zity
 
  Number Comparator
  Name : -5 ). Fcity
  Name : 3 ). Rcity
  Name : 4 ). Zity
  Name : 10 ). Acity
  Name : 25 ). Bcity
  Name : 99 ). Kcity
 
Note: Sorting of the Arrays class is as the same as the Collections.

Hope you learnt something new today .

Happy Coding

No comments:

Post a Comment