Loading
Comparable-and-Comparator-Interface

Comparable Interface

The Comparable interface is a predefined interface int he java.lang package that is used to define the natural ordering of objects.

Features

  • Introduced from JDK1.2 
  • Comparable is used to compare objects and sort them.
  • Comparable is generally used to perform default sorting.
  • The Comparable interface has an abstract method called as compareTo() method.
  • compareTo() return ‘-1’ when the values are lesser than, ‘0’ when the values are the same, and ‘+1’ when the values are greater than.

Syntax:

 public int compareTo(element e); 

Rules For Using Comparable Interface

  • The class has to implement a comparable Interface.
  • Import Comparable Interface from Java.Lang package.
  • Specify the generic type of which object to be compared.
  • Override the compareTo() in such a way it has the logic of sorting. 

Example: Sorting Student Objects by Name

package quipoin;

public class Student implements Comparable<Student> {
	public int id;
	public String name;
	public int age;

	public Student(int id, String name, int age) {
		this.id = id;
		this.name = name;
		this.age = age;
	}

	@Override
	public String toString() {
		return id + "\t" + name + "\t" + age;
	}

	@Override
	public int compareTo(Student std) {
		// return this.id - std.id;                          // sorting based on the id
		return this.name.compareTo(std.name);                // sorting based on the name
	}
}
package quipoin;

import java.util.TreeSet;

public class TestStudent {
	public static void main(String[] args) {
		Student s1 = new Student(102, "Charan", 25);
		Student s2 = new Student(103, "Abhi", 15);
		Student s3 = new Student(101, "Bharath", 30);

		TreeSet<Student> ts = new TreeSet<>();
		ts.add(s1);
		ts.add(s2);
		ts.add(s3);

		System.out.println("Student records:");
		System.out.println("--------------------");
		System.out.println("Id\tName\tAge");
		System.out.println("--------------------");

		for (Student std : ts) {
			System.out.println(std);
		}
	}
}


Output:

Student records:
--------------------
Id	Name	Age
--------------------
103	Abhi	15
101	Bharath	30
102	Charan	25

Explanation

In the above example Student details are compared and sorted based on Id, we can also compare and sort based on other fields also as Name and Age. The code for that is written in the comments.

Comparator Interface

The Comparator interface is a predefined interface in the java.util package that allows custom sorting of objects

Features

  • It was introduced from JDK1.2
  • A comparator is used for comparing the objects and performing custom sorting.
  • The comparator interface has an abstract method called as compare() method.


Syntax: 

public int compare(element e1, element e2);

Rules For Using Comparator Interface

  • The class has to implement a comparator Interface.
  • Import Comparator Interface from java.util package.
  • Specify the generic type of object that needs to be compared.
  • Create an object of that specific class and pass the object reference as a parameter to the constructor.
  • Override the compare() method to provide the sorting logic.

Example: Sorting Mobile Objects by Brand and Price

package quipoin;

public class Mobile {

	public String brand;
	public double price;

	public Mobile(String brand, double price) {
		this.brand = brand;
		this.price = price;
	}

	@Override
	public String toString() {
		return brand + "\t" + price;
	}
}
package quipoin;

import java.util.Comparator;

public class SortByBrand implements Comparator<Mobile>{
	
	@Override
	public int compare(Mobile m1, Mobile m2) {
		return m1.brand.compareTo(m2.brand);
	}
}
package quipoin;

import java.util.Comparator;

public class SortByPrice implements Comparator<Mobile> {
	
	@Override
	public int compare(Mobile m1, Mobile m2) {
		return (int) (m1.price - m2.price);
	}
}
package quipoin;

import java.util.Iterator;
import java.util.TreeSet;

public class TestMobile {

	public static void main(String[] args) {
		Mobile m1 = new Mobile("Samsung", 22500.00);
		Mobile m2 = new Mobile("Iphone", 152500.00);
		Mobile m3 = new Mobile("Nokia", 15500.00);
		Mobile m4 = new Mobile("Realme", 18500.00);

		// SortByBrand br=new SortByBrand();
		SortByPrice pr = new SortByPrice();
		TreeSet<Mobile> ts = new TreeSet<>(pr);

		ts.add(m1);
		ts.add(m2);
		ts.add(m3);
		ts.add(m4);

		System.out.println("Mobile details:");
		System.out.println("-----------------");
		System.out.println("Brand\tPrice");
		System.out.println("-----------------");
		Iterator<Mobile> it = ts.iterator();
		while (it.hasNext()) {
			System.out.println(it.next());
		}
	}
}


Output:

Mobile details:
-----------------
Brand	Price
-----------------
Iphone	152500.0
Nokia	15500.0
Realme	18500.0
Samsung	22500.0

Explanation

  • The mobiles are sorted by price in ascending order.
  • If we use sortByBrand, they will be sorted alphabetically by brand.

Difference between Comparable Vs Comparator

Comparable

Comparator

  • Comparable Interface present in java. lang package.
  • Comparator Interface present in java. util package.
  • It provides single sorting sequence and it is known as default sorting.
  • It provides multiple sorting sequences and it is known as custom sorting.
  • Objects are mutually comparable in nature.
  • Objects are not mutually comparable in nature.
  • Comparable provides compareTo() method to sort the elements.
  • Comparator provides compare() method to sort the elements.

 

Two Minute Drill

  • Use Comparable when objects have a natural order (default sorting).
  • Use Comparator when sorting criteria need to be customized or changed dynamically.
  • TreeSet and TreeMap rely on either Comparable or Comparator for ordering elements.