DEV Community

rajubora
rajubora

Posted on

Comparable and Comparator in Java

In java-8 comparable and comparator interface are used for sorting object using custom logic .
However there are some diffrences between them listed as below :

Comparable Interface :

  • For implementing comparable interface we have to override the compareTo() method.

  • CompareTo method takes only one arguement, which is the object being compared.

  • This CompareTo method has to be implemented in the class to define the natural ordering of the objects.

  • It allow us to define single sorting criteria.

  • Interface Signature :

public interface Comparable<T> {
    public int compareTo(T o);
}

Enter fullscreen mode Exit fullscreen mode

Comparator Interface :

  • For implementing Comparator interface we have to override the compare() method of the interface.

  • This method takes two parameters and compares them (o1 and o2)
    and returns:

a negative integer if o1 is less than o2.
zero if o1 is equal to o2.
a positive integer if o1 is greater than o2.
  • It allow is to define multiple sorting criteria and can be used to sort object in diffrent ways.

  • Interface Signature :

public interface Comparator<T> {
    public int compare(T o1, T o2);
}

Enter fullscreen mode Exit fullscreen mode

Example :

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

// Example class representing a Student
class Student implements Comparable<Student> {
    private String name;
    private int id;
    private int age;

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

    // Getters
    public String getName() {
        return name;
    }

    public int getId() {
        return id;
    }

    public int getAge() {
        return age;
    }

    // Implementing Comparable interface based on student id
    @Override
    public int compareTo(Student other) {
        return Integer.compare(this.id, other.id);
    }

    // toString method for displaying student details
    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", id=" + id +
                ", age=" + age +
                '}';
    }
}

// Comparator to sort students by age
class AgeComparator implements Comparator<Student> {
    @Override
    public int compare(Student s1, Student s2) {
        return Integer.compare(s1.getAge(), s2.getAge());
    }
}

public class ComparableComparatorExample {
    public static void main(String[] args) {
        // Creating a list of students
        List<Student> students = new ArrayList<>();
        students.add(new Student("Ram", 101, 20));
        students.add(new Student("Shyam", 102, 22));
        students.add(new Student("Raj", 103, 21));
        // Sorting students using Comparable (by student id)
        Collections.sort(students);
        System.out.println("Students sorted by ID (Comparable):");
        for (Student student : students) {
            System.out.println(student);
        }

        // Sorting students using Comparator (by age)
        Collections.sort(students, new AgeComparator());
        System.out.println("\nStudents sorted by Age (Comparator):");
        for (Student student : students) {
            System.out.println(student);
        }
    }
}


Enter fullscreen mode Exit fullscreen mode

In above Example :

  • The Student class implements the Comparable interface based on the student ID. This allows sorting a list of students by their IDs.
  • The AgeComparator class implements the Comparator interface to provide custom sorting logic based on student ages.
  • In the main method, we create a list of Student objects and sort them first using the natural ordering defined by Comparable and then using the custom ordering defined by Comparator.

Top comments (0)