Java Design Pattern
Introduction to Java 10
Introduction to Java 11
Introduction to Java 12

JAVA Comparator Interface

It is an in-built interface present in java.util package.
It defines two methods like compare() and equals().
The general form of compare() is;
public int compare(Object ob1, Object ob2)
returns +ve value, when ob1 is coming before ob2.
returns -ve valie, when ob1 is coming after ob2.
returns 0, when ob1 equals ob2.

public boolean equals() :

  • • Whenever we are implementing Comparator interface, compulsory we should provide implementation for compare() method.
  • • Implementing equals() method is optional, because it is already available in every java class from Object class through inheritance.

Let’s see the following example for getting better clarity on Comparator.

package java8s; 
import java.util.*;
public class ComparatorDemo
{
public static void main(String[] args) {

TreeSet<Integer> t= new TreeSet<>(new MyComparator());

t.add(30);
t.add(70);
t.add(50);
t.add(45);

System.out.println(t);
}
}
class MyComparator implements Comparator
{
public int compare(Object ob1, Object ob2)
{
Integer i1=(Integer)ob1;
Integer i2=(Integer)ob2;

if(i1<i2)
{
return +1;
}

else if(i1>i2)
{
return -1;
}
else
{
return 0;
}
}
}

Output

[70, 50, 45, 30]
[data items are arranging in the form of descending order]



About the Author



Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.


We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc






 PreviousNext