Comparator in Java

By | 2015-04-29T10:29:35+05:30 April 29th, 2015|java|

Comparator in Java is an interface, which was coming from java.util package, used to ordering the collection of objects.

In order to compare the set of elements in an object , The comparator provides the multiple sorting sequences. Hence we can sort the object based on any property.

Methods in Comparator

public int compare(Object o1,Object o2);

The method comparing the two arguments and returns the below values.

In the case of first element less than of second element  it returns   “-1”;

In the case of first element equals to second element, it returns   “0”;

In the case of first element greater than of second element, it returns   “1”;

unlike the Comparable, A class whose objects are to be arranged has not to implement  the comparator interface. Rather, some third class can include this interface to arrange. For instance “City” class ought to implement Comparable to indicate group of city objects via its ID. while in Comparator, class whose object need to be arranged doesn’t implement this interface. where as other class can implement this interface like CityComparator.

Comparator Example

Creating a City class, we are going to sort the city objects.

class City {

    int id;
    String city;

    public City(int id, String city) {
        this.id = id;
        this.city = city;
    }
}

Creating the CityComparator, which implements the Comparator interface to provide the bean comparison mechanism.

class CityComparator implements Comparator<City> {

    @Override
    public int compare(City o1, City o2) {
        if (o1.id == o2.id) {
            return 0;
        } else if (o1.id > o2.id) {
            return 1;
        } else {
            return -1;
        }
    }

}

The ComparatorDemo is a class from which we can access the City class.


/**
*
* @author chandrashekhar
*/
public class ComparatorDemo {

    public static void main(String[] args) {
        List<City> l = new ArrayList<City>();
        l.add(new City(1, "Vijayawada"));
        l.add(new City(5, "Mumbai"));
        l.add(new City(4, "Visakhapatnam"));
        l.add(new City(2, "Delhi"));
        int size = l.size();
        System.out.println("Before Comparator");
        for (int i = 0; i < size; i++) {
            City city = l.get(i);
            System.out.print(city.id + " ");
            System.out.print(city.city + " ");
        }
        System.out.println("\n After Comparator");
        Collections.sort(l, new CityComparator());
        System.out.println("");
        for (int i = 0; i < size; i++) {
            City city = l.get(i);
            System.out.print(city.id + " ");
            System.out.print(city.city + " ");
        }
    }
}

 Output:

Before Comparator

1 Vijayawada 5 Mumbai 4 Visakhapatnam 2 Delhi

After Comparator
1 Vijayawada

2 Delhi

4 Visakhapatnam

5 Mumbai

Comparing Two Different Beans

The main advantage of the Comparator is to compare the two bean properties. Hence we can compare the two different beans using Comparator but both two are the same type. The bellow example for comparing the Cat Object with Elephant Object and both are the Animal Type.

Creating Animal Class which implements the Comparator interface.


import java.util.Comparator;

/**
 *
 * @author chandrashekhar
 */
public class Animal implements Comparable<Animal> {

    private int id;
    private String name;

    public Animal() {
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    @Override
    public int compareTo(Animal animal) {
        int result = 0;
        try {
            if (getId() < animal.getId()) {
                result = -1;
            } else if (getId() == animal.getId()) {
                result = 0;
            } else {
                result = 1;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}

Create the Cat and Elephant classes. Here I am not implementing any methods. Because I am using dynamic method dispatch (Assigning the sub class object to super class reference).


public class Cat extends Animal {

}

public class Elephant extends Animal {

}

Create SortDemo.java, from which we can access the Animal Object.


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

/**
 *
 * @author chandrashekhar
 */
class SortDemo {

    public static void main(String[] args) {
        List<Animal> animal_list = null;
        Animal animal = null;
        try {
            animal_list = new ArrayList<Animal>();

            animal = new Cat();
            animal.setId(5);
            animal.setName("cat");
            
            animal_list.add(animal);
            
            animal = new Cat();
            animal.setId(1);
            animal.setName("small cat");

            animal_list.add(animal);

            animal = new Elephant();
            animal.setId(8);
            animal.setName("Big Elephant");

            animal_list.add(animal);

            animal = new Elephant();
            animal.setId(3);
            animal.setName("Elephant");

            animal_list.add(animal);

            Collections.sort(animal_list);

            for (Animal current_animal : animal_list) {
                System.out.println("Animal id: " + current_animal.getId() + " is " + current_animal.getName());
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            animal = null;
            animal_list = null;
        }
    }
}

Output

Animal id: 1 is small cat
Animal id: 3 is Elephant
Animal id: 5 is cat
Animal id: 8 is Big Elephant

You May Like This :  How Comparable works in Java

About the Author:

Hi Folks, you have reach this so far, that shows you like what you are learning. Then why don't you support us to improve for bettor tutorials by leaving your valuable comments and why not you keep in touch with us for latest updates on your favorite blog @ facebook , twitter , Or Google+ ,

Leave A Comment