top

Search

Java Tutorial

.

UpGrad

Java Tutorial

Comparable And Comparator in Java

Introduction

Comparables and Comparators in Java are vital concepts that help work with collections. Comparables are objects used to compare objects to each other with the compareTo() method. Contrary to that, Comparators allow sorting out objects in the same order.

Comparables and comparators are valuable when sorting, searching, and comparing data. For instance, elements in an array or a collection can be compared using these methods. 

This tutorial will examine a few examples of comparators and comparables and discuss how these interfaces are crucial to a programmer’s skill set.

Overview

Java offers two different interfaces for sorting objects. These include - Comparable and comparator interfaces. 

While the comparable interface is used to order the objects of a class implementing it, the comparator interface orders the objects of two given different classes.

Both interfaces can be used when it is necessary to sort objects per specific criteria. The comparable interface in Java provides an ordering based on the natural sequence of the objects. On the other hand, the comparator interface employs custom sorting.

What is Comparable in Java? 

As a member of java.lang, the package contains only one compareTo (Object) method for comparing two objects. The comparable interface is Java, an highly valuable interface that imposes an ordering of different objects.

The comparable interface imposes a uniform ordering on all objects included in a class. It offers a single sorting sequence. The user can mark their objects using defined classes. 

For instance, you can quickly sort the Employee objects based on their identification, age, name, and other data. 

However, you can do so based on a single data member only. The comparable interface is utilized for classes like Arrays.sort() and Collections.sort() as these provide a parameter for sorting objects.

Methods Used in Comparable

As an interface, it uses a single method for comparing and sorting data. This method is named compareTo() and is a valuable parameter for comparing and sorting data.

  • compareTo() 

The compareTo() method compares two strings lexicographically. It regards objects as arguments and returns an integer value based on the strings’ alphabetical order.

This method is generally used to sort objects in a collection in collections like TreeSet and TreeMap. When implemented, the method returns a value telling the programmer whether the first argument is smaller, equal to, or greater than the second argument.

If the first string is greater than the second string, it shows a positive number. Similarly, if the first string is less than the second string, it displays a negative number. Finally, if the first string equals the second string, it shows ‘0’.

int compareTo(T o1);

Example of Comparable in Java 

Here is an example of a comparable in Java:

package com.journaldev.sort;
import java.util.Comparator;
public class Employee implements Comparable<Employee> {
    private int employeeId;
    private char[] employeeName;
    private byte employeeAge;
    private double employeeSalary;
    public int getEmployeeId() {
        return employeeId;
    }
    public char[] getEmployeeName() {
        return employeeName;
    }
    public byte getEmployeeAge() {
        return employeeAge;
    }
    public double getEmployeeSalary() {
        return employeeSalary;
    }
    public Employee(int id, char[] name, byte age, double salary) {
        this.employeeId = id;
        this.employeeName = name;
        this.employeeAge = age;
        this.employeeSalary = salary;
    }
    @Override
    public int compareTo(Employee emp) {
        //let's sort the employee based on an id in ascending order
        //returns a negative integer, zero, or a positive integer as this employee id
        //is less than, equal to, or greater than the specified object.
        return (this.employeeId - emp.employeeId);
    }
    @Override
    //this is required to print the user-friendly information about the Employee
    public String toString() {
        return "[id=" + this.employeeId + ", name=" + new String(this.employeeName) + ", age=" + this.employeeAge + ", salary=" +
                this.employeeSalary + "]";
    }
}

What is Comparator in Java? 

The comparator is an essential interface in the Java.util package for comparing two objects. It contains compare(Object obj1, Object obg2) and equals(Object element). 

While the compare() method includes comparing two objects and returns values based on parameters, the equals() method checks if two objects are equal. The equals() method, however, returns a boolean value.

What is the comparator interface used for?

The comparator interface sorts objects using a natural sorting order which is helpful in the case of user-defined classes. It is done by overriding the compare() method and specifying custom sorting logic for all objects.

The comparator interface is a vital part of the JavaAPI and is used to sort objects not containing a natural sorting order. It can be used along with Collections.sort() and Stream.sorted() methods for the best results.

Methods Used in Comparator  

The comparator uses one method to analyze its data. It is called compare() and is discussed below.

compare() 

Compare() compares two objects in an array to determine the greater one. This method can be used in sorting algorithms, such as quicksort and mergesort, which require sorting elements before a comparison. 

It can be used to compare objects and data types. The compare() method can also determine if two objects are equal, which can be helpful in terms of binary search trees and hash tables.

int compare(T o1, T o2);

The comparator predicts the sorting order focusing on the returned integer value. For instance,

1. Positive if the value of the first object exceeds that of the second object.

2. Negative if the value of the first object is smaller than that of the second object.

3. 0 if the values of both objects are equally defined.

Equals

Equals() is a method used to determine if two objects have the same value. When implemented, this method results in a boolean telling the programmer if the result is either true or false. 

The equals() method uses == to compare references of objects and their values.

comparator1.equals(comparator2);

Note: When comparing primitive types, you can use the == operator and the equals() method for comparing objects.

Comparing() and thenComparing()

The comparing() method is a utility used in Java 9 library. It allows programmers to compare two objects based entirely on their properties. It uses natural ordering and can be assigned by a comparator. 

At the same time, programmers can compare objects using multiple fields in a single collection.

Comparator comparing(Function keyExtractor);

Where the keyExtractor is the function used for extracting comparable data.

thenComparing()

thenComparing() is a method in comparator that allows for chaining multiple comparators. It is done in a more complex way as compared to Comparing(). It does so by taking one comparator and returning a new comparator. 

This new comparator sorts by the first and then the second in case the first one returns a 0 result.

Comparator thenComparing(Function keyExtractor, Comparator keyComparator); where the keyExtractor extracts the comparable key and the keyComparator compares the key.

Example of Comparator in Java 

A comparable example in Java 8 is stated below:

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class ComparatorExample {
    public static void main(String[] args) {
        List<Employee> employees = new ArrayList<>();
        employees.add(new Employee(1010, "Melissa", 120000.00, LocalDate.of(2012, 8, 11)));
        employees.add(new Employee(1004, "Greta", 80000.50, LocalDate.of(2017, 4, 11)));
        employees.add(new Employee(1015, "Ananya", 170000.00, LocalDate.of(2019, 10, 21)));
        employees.add(new Employee(1009, "Alberto", 110000.00, LocalDate.of(2013, 9, 23)));
        System.out.println("Employees : " + employees);
        // Sort employees by Name
        Collections.sort(employees, Comparator.comparing(Employee::getName));
        System.out.println("\nEmployees (Sorted by Name) : " + employees);
        // Sort employees by Salary
        Collections.sort(employees, Comparator.comparingDouble(Employee::getSalary));
        System.out.println("\nEmployees (Sorted by Salary) : " + employees);
        // Sort employees by JoiningDate
        Collections.sort(employees, Comparator.comparing(Employee::getJoiningDate));
        System.out.println("\nEmployees (Sorted by JoiningDate) : " + employees);
        // Sort employees by Name in descending order
        Collections.sort(employees, Comparator.comparing(Employee::getName).reversed());
        System.out.println("\nEmployees (Sorted by Name in descending order) : " + employees);
        // Chaining multiple Comparators
        // Sort by Salary. If Salary is same then sort by Name
        Collections.sort(employees, Comparator.comparingDouble(Employee::getSalary)
                                    .thenComparing(Employee::getName));
        System.out.println("\nEmployees (Sorted by Salary and Name) : " + employees);
    }
}
class Employee {
    private int employeeId;
    private String employeeName;
    private double employeeSalary;
    private LocalDate joiningDate;
    public Employee(int employeeId, String employeeName, double employeeSalary, LocalDate joiningDate) {
        this.employeeId = employeeId;
        this.employeeName = employeeName;
        this.employeeSalary = employeeSalary;
        this.joiningDate = joiningDate;
    }
    public int getEmployeeId() {
        return employeeId;
    }
    public String getEmployeeName() {
        return employeeName;
    }
    public double getEmployeeSalary() {
        return employeeSalary;
    }
    public LocalDate getJoiningDate() {
        return joiningDate;
    }
    @Override
    public String toString() {
        return "Employee [ID=" + employeeId + ", Name=" + employeeName + ", Salary=" + employeeSalary
                + ", JoiningDate=" + joiningDate + "]";
    }
}

Difference Between Comparable and Comparator

Comparable

Comparator

  • Comparable is used to compare two objects in the same class.

  • A Comparator compares two objects across several different classes.

  • Using comparison, a programmer can sort out objects with natural ordering.

  • Comparator interfaces allow the programmer to use custom orders.

  • The Comparable interface uses the compareTo(Object) method.

  • Comparator uses the compare(Object) method.

  • Comparable is a unique part of the Java collection framework.

  • Comparator doesn’t include itself in the Java collection.

  • A Comparable interface in Java is available in the java.lang package.

  • Programmers can find the Comparator interface in the java.util package.

  • Comparable is only used for internal sorting.

  • Comparator allows programmers to use external sorting.

  • Comparable is a predefined interface.

  • Comparator is a user-defined interface.

  • Comparable only offers a single sorting sequence for objects in a collection.

  • Comparator provides several sorting sequences for the objects.

  • Comparable is well-suited for a minuscule number of elements.

  • Comparator helps out with a large number of elements.

  • Comparable is much slower compared as it uses reflection.

  • Comparator is exceptionally faster as it uses a direct comparison.

Conclusion

Since it is clear why we use Comparable and Comparator interfaces in Java, it is a good time to start learning and implementing these interfaces and their methods. If you’re a Java developer looking to compare and sort objects, you should learn about comparables and comparators. 

Comparable and comparator are both interfaces in Java language used for sorting object collection. Not only are these two highly efficient interfaces, but they’re also extremely helpful in getting your job done quickly. 

Knowing how to use these interfaces can help programmers develop programs rapidly with the help of sorting and comparison.

FAQs

1. What is the primary difference between Comparable And Comparator in Java?

This is one of the most common comparable vs comparator Java interview questions. Comparable is an interface used to sort objects with the help of natural ordering. On the other hand, the comparator helps sort different objects with a custom sorting order.

2. Does Comparator come in ‘class’ or ‘interface’?

A comparator is an interface, not a class. It is a method for comparing two objects to determine their order and is typically used to sort different collections of objects.

3. How many methods does the Comparable Interface implement?

As an interface, the comparable interface implements a single method called compareTo(Object). This method can be implemented using any class compatible with the comparable Interface.

Leave a Reply

Your email address will not be published. Required fields are marked *