Comparator Interface in java


If you want to define our own sorting we havwet to implement comparator interface.
This interface present in java.util package.
This interface contain the following two methods.
1.public int compare(Object o1,Object o2)
return –ve number if o1 comes before o2.
return +ve number If o1 comes after o2.
returns zero if o1 and o2 equal.
2.public Boolean equals(Object o)
by using comparator interface we can define our own customized sorting.

Write a program to insert integer object in the TreeSet where the Sorting technique is descending order.

import java.util.*;
class TreeSetDemo
{
public static void main(String arg[])
{
TreeSet t=new Treeset(new MyComparator());
t.add(new Integer(20));
t.add(new Integer(10));
t.add(new Integer(30));
t.add(new Integer(100));
System.out.println(t); // 10 ,20 ,30,100
}
}
class MyComparator implements Comparator
{
public int Compare(Object o1,Object o2)
{
Integer i1=(Integer)o1;
Integer i2=(Integer)o2;
int i1=i1.intValue();
int i2=i2.intValue();
if(i1>i2)
return -1;
else
if(i1 > i2)
return +1;
else
return 0;
}
}

write a program to insert string objects into the TreeSet where the sorting order is increasing order of String lengths.

import java.util.*;
class ComparatorDemo
{
public static void main(String arg[])
{
TreeSet t=new Treeset(new Mycomparator())
t.add(“aaaaaa”);
t.add(“bbbb”);
t.add(“ccc”);
System.out.println(t); // [ccc,bbbb,aaaaaa]
}
}
class MyComparator implements Comparator
{
public int compare(Object o1,Object o2)
{
String s1=(String)o1;
String s2=(String)o2;
if(s1.length() < s2. length())
return -1;
else
if(s1.length() > s2.length())
return +1;
else
return 0;
}
}

program to insert StringBuffer Objects in the treeSet according to dictionary order

import java.util.*;
class ComparatorDemo
{
public static void main(String arg[])
{
TreeSet t=new TreeSet(new MyComparator());
t.add(new StringBuffer(“aaa”);
t.add(new StringBuffer(“bbb”);
t.add(new StringBuffer(“ccc”);
t.add(new StringBuffer(‘ddd”);
System.out.println(t);
}
}
class MyComparator implements Comparator
{
public int compare(Object o1,Object o2)
{
String s1=o1.toString();
String s2=o2.toString();
return s1.compareTo(s2);
//return s2.compareTo(s1);
}
}

if we return always like this:
return 0; // aaa
return +100 // bbb,ccc,aaa,ddd
return -100 // ddd,aaa,ccc,bbb


Enter your email address to get our daily JOBS & INTERVIEW FAQ's Straight to your Inbox.

Make sure to activate your subscription by clicking on the activation link sent to your email