View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

CompareTo in Java

Updated on 17/03/20256,710 Views

As Java developers, we frequently need to arrange items that are organized in a collection. Java enables us to apply different sorting algorithms to any kind of data. The Java compareTo method is essential in Java development and assists the developer in organizing complex objects and establishing custom sorting criteria. Without it, managing intricate objects becomes challenging. Therefore, it is an essential tool that every Java developer should possess in their toolkit. 

As a component of the 'comparable' interface in Java, the 'compareTo' method establishes the natural ordering of objects in a class. By employing this approach, you can arrange or specify custom objects beneficially and clearly to minimize confusion and simplify development. 

The CompareTo in Java is frequently utilized to sort collections and establish the relative sequence of objects by assessing their values. It's an essential component of the Comparable interface, permitting objects to be contrasted with one another. 

Improve your Java programming skills with our Software Development courses — take the next step in your learning journey! 

Below we discuss the Ins and Outs of CompareTo()  function in Java. Keep on reading!

Prerequisites

Prior to initiating a CompareTo in Java, it's essential to grasp several fundamental concepts and requirements. Here’s a list of information you ought to be aware of: 

Fundamental Java Understanding

You need to be familiar with Java syntax, variables, and control structures, including loops and conditionals. 

  • Classes and Objects: Learn to define classes, generate objects, and utilize methods. 
  • Packages: Learn how to structure your code into packages for improved code organization. 

Grasping Comparable and Comparator Interfaces 

  • Comparable Interface: Discover the Comparable<T> interface, which specifies the compareTo() method for the natural ordering of objects. 
  • compareTo() Method: Learn how the compareTo() method functions, what its return values are, and the appropriate scenarios for its application (it should yield: 

~ A negative integer if the current object is smaller than the argument object. 

~ Zero if the present object matches the argument object. 

~ A positive integer if the present object exceeds the argument object). 

  • Comparator Interface: Understand when to utilize Comparator, particularly when custom sorting is required, and you cannot alter the class that is being sorted. 

Principles of Object-Oriented Programming (OOP) 

  • Encapsulation: Comprehend the way classes communicate with one another and how to utilize getter and setter methods for private attributes. 
  • Inheritance and Polymorphism: Understand how inheritance functions in Java and how polymorphism can be applied with compareTo and Comparator. 
  • Override Methods: Understand the @Override annotation and the correct way to override methods such as compareTo() within your classes. 

Organizing and Data Frameworks 

  • Collections: Learn how to work with ArrayList, LinkedList, HashMap, etc., as you will probably need to organize collections in the project. 
  • Sorting Algorithms: While not absolutely necessary, having a rudimentary grasp of sorting algorithms such as QuickSort, MergeSort, or BubbleSort can aid in comprehending the underlying mechanics of sorting. 
  • Collections.sort(): Understand how to utilize Collections.sort() or Arrays.sort() to sort objects that implement Comparable or when a Comparator is supplied. 

Development Tools

  • IDE: Configure a Java development setup, like IntelliJ IDEA, Eclipse, or VSCode, to code, debug, and execute your project. 
  • Build Tools (Optional): Get to know tools such as Maven or Gradle for managing projects, particularly if your project will involve various dependencies. 

Also Read: Careers in Java: How to Make a Successful Career in Java in 2025

What is the compareTo() Method?

The method compareTo() evaluates two strings in a lexicographical manner. The comparison relies on the Unicode value assigned to each character within the strings. 

The method yields 0 if the string matches the other string. A value below 0 is returned if the string has fewer characters than the other string, while a value above 0 is returned if the string has more characters than the other string. 

Syntax

public int compareTo(String string2)
public int compareTo(Object object)

Parameter Values

  • string2: A String, representing the other string to be compared
  • object: An Object, representing an object to be compared

Technical Details

Returns: An int value: 

  •  if the string is equal to the other string.
  • < 0 if the string is lexicographically less than the other string
  • > 0 if the string is lexicographically greater than the other string (more characters)

Also Read: What is Composition in Java With Examples 

Using compareTo() with Built-in Java Classes

Comparing Strings using compareTo()

In Java, the compareTo() method allows for the lexicographical comparison of String objects (i.e., according to their Unicode values). The compareTo() function is specified in the Comparable interface, which is implemented by the String class. It examines two strings letter by letter and produces an integer outcome based on their lexicographic sequence. 

Syntax of compareTo() for Strings:

int compareTo(String anotherString)

Return Values:

  • 0: If the strings are equal.
  • Negative integer: If the string that is being called (this) is lexicographically smaller than the parameter (anotherString). 
  • Positive integer: If the string invoked (this) is lexicographically larger than the argument (anotherString). 

How It Operates: 

It evaluates the strings one character at a time, according to their Unicode values. 

The comparison concludes when: 

  • A variation is observed among characters in the same location. 
  • One string is depleted, while the other still contains characters. 

Example:

public class CompareToExample {
    public static void main(String[] args) {
        String str1 = "apple";
        String str2 = "banana";
        String str3 = "apple";
        // Comparing str1 and str2
        System.out.println("str1.compareTo(str2): " + str1.compareTo(str2));  // Negative value because "apple" is less than "banana"
        // Comparing str1 and str3
        System.out.println("str1.compareTo(str3): " + str1.compareTo(str3));  // 0 because both strings are equal
        // Comparing str2 and str1
        System.out.println("str2.compareTo(str1): " + str2.compareTo(str1));  // Positive value because "banana" is greater than "apple"
    }
}

Output:

str1.compareTo(str2): -1
str1.compareTo(str3): 0
str2.compareTo(str1): 1

Explanation:

  • str1.compareTo(str2): "apple" is lexicographically smaller than "banana" (because 'a' < 'b'), so the result is a negative integer.
  • str1.compareTo(str3): Both strings are exactly the same, so the result is 0.
  • str2.compareTo(str1): "banana" is lexicographically greater than "apple" (because 'b' > 'a'), so the result is a positive integer.

Comparing Wrapper Classes (Integer, Double)

In Java, you can utilize the compareTo() method to compare wrapper classes such as Integer, Double, and additional numeric wrappers. These wrapper classes implement the Comparable<T> interface, enabling them to be compared with one another through the compareTo() method. 

Key Details: 

  • Integer: A wrapper for the primitive int type. 
  • Double: A wrapper for the double primitive data type. 

Both of these classes implement the Comparable<T> interface, which means they possess a compareTo() method that can be utilized to compare their values. 

Syntax of compareTo() for Wrapper Classes:

int compareTo(T anotherObject)

Where T is the type of the object (e.g., Integer, Double, etc.).

Return Values:

  • If the two wrapper objects are equal, the return value will be zero.
  • If the calling object is less than the argument object, the return value will be a negative integer.
  • If the calling object is greater than the argument object, the return value will be a positive integer.

Example:

public class IntegerCompare {
    public static void main(String[] args) {
        Integer num1 = 5;
        Integer num2 = 10;
        Integer num3 = 5;
        // Comparing num1 and num2
        System.out.println("num1.compareTo(num2): " + num1.compareTo(num2));  // Negative, 5 < 10
        // Comparing num1 and num3
        System.out.println("num1.compareTo(num3): " + num1.compareTo(num3));  // 0, 5 == 5
        // Comparing num2 and num1
        System.out.println("num2.compareTo(num1): " + num2.compareTo(num1));  // Positive, 10 > 5
    }
}

Output:

num1.compareTo(num2): -1
num1.compareTo(num3): 0
num2.compareTo(num1): 1

Explanation:

  • num1.compareTo(num2): 5 is less than 10, so the result is negative (-1).
  • num1.compareTo(num3): Both are equal (5 == 5), so the result is 0.
  • num2.compareTo(num1): 10 is greater than 5, so the result is positive (1).

Example of Comparing Double:

public class DoubleCompare {
    public static void main(String[] args) {
        Double d1 = 5.5;
        Double d2 = 10.5;
        Double d3 = 5.5;
        // Comparing d1 and d2
        System.out.println("d1.compareTo(d2): " + d1.compareTo(d2));  // Negative, 5.5 < 10.5
        // Comparing d1 and d3
        System.out.println("d1.compareTo(d3): " + d1.compareTo(d3));  // 0, 5.5 == 5.5
        // Comparing d2 and d1
        System.out.println("d2.compareTo(d1): " + d2.compareTo(d1));  // Positive, 10.5 > 5.5
    }
}

Output:

d1.compareTo(d2): -1
d1.compareTo(d3): 0
d2.compareTo(d1): 1
Explanation:

Explanation:

  • d1.compareTo(d2): 5.5 is less than 10.5, so the result is negative (-1).
  • d1.compareTo(d3): Both are equal (5.5 == 5.5), so the result is 0.
  • d2.compareTo(d1): 10.5 is greater than 5.5, so the result is positive (1).

Also Read: Transient in java: What is, How Does it Work?

Implementing compareTo() in a Custom Class

To create the compareTo() method in a custom class in Java, you should adhere to these steps: 

  • Implement the Comparable<T> Interface: Your class needs to implement the Comparable<T> interface, with T representing the type of object you are comparing (in this scenario, the custom class). 
  • Override the compareTo() Method: You need to override the compareTo() method to establish how two objects of your class ought to be compared. 

General Syntax for compareTo():

public class MyClass implements Comparable<MyClass> {
    @Override
    public int compareTo(MyClass other) {
        // Comparison logic
    }
}

The compareTo() method:

  • Returns a negative integer if the current object is less than the argument.
  • Returns 0 if the current object is equal to the argument.
  • Returns a positive integer if the current object is greater than the argument.

Example: Implementing compareTo() in a Custom Class

Let’s define a basic class Person that includes attributes for name and age. We will define compareTo() to ensure that Person objects are compared according to their age. 

Step-by-Step Code:

public class Person implements Comparable<Person> {
    private String name;
    private int age;
    // Constructor
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    // Getter methods
    public String getName() {
        return name;
    }
    public int getAge() {
        return age;
    }
    // Overriding the compareTo() method to compare by age
    @Override
    public int compareTo(Person other) {
        // Compare ages (this.age - other.age)
        return Integer.compare(this.age, other.age);
    }
    // toString() method for better output
    @Override
    public String toString() {
        return "Person{name='" + name + "', age=" + age + "}";
    }
    public static void main(String[] args) {
        // Create some Person objects
        Person person1 = new Person("Alice", 30);
        Person person2 = new Person("Bob", 25);
        Person person3 = new Person("Charlie", 30);
        // Compare the persons
        System.out.println(person1.compareTo(person2)); // Positive because 30 > 25
        System.out.println(person1.compareTo(person3)); // Zero because 30 == 30
        System.out.println(person2.compareTo(person1)); // Negative because 25 < 30
    }
}

Explanation:

Class Implementation: The Person class realizes the Comparable<Person> interface. 

compareTo() Function: 

We assess two Person objects by their age attribute. 

The Integer.compare(this.age, other.age) function is utilized to reliably compare the ages, guaranteeing that the outcome aligns with the agreement of compareTo(). 

  • If the age values match, the method outputs 0. 
  • If this.age is higher, the method yields a positive value. 
  • If this. age is smaller, the method yields a negative value. 

toString() Method: This is implemented to offer a clearer output when displaying Person objects. 

Output:

5
0
-5
  • person1.compareTo(person2): Since person1 (30) is older than person2 (25), the result is positive.
  • person1.compareTo(person3): Since both are of the same age (30), the result is 0.
  • person2.compareTo(person1): Since person2 (25) is younger than person1 (30), the result is negative.

Sorting Using compareTo()

In Java, the compareTo() method compares objects, which is crucial for sorting objects in collections or arrays. The compareTo() function is included in the Comparable<T> interface, and when a class implements it, it establishes the natural order of that class's objects. 

By implementing the CompareTo in Java, it can automatically utilize it for sorting, including using the Collections.sort() method for List instances or the Arrays.sort() method for arrays. 

Syntax of compareTo()

int compareTo(T other)

T represents the type of the object under comparison (such as String, Integer, or any user-defined class). 

The other is the item being contrasted with the current item (this). 

Creating compareTo() in a Custom Class 

To sort custom objects with compareTo(), the class needs to implement the Comparable<T> interface and override the compareTo() method. For instance, let's define a class Person in which we will assess objects based on their age. 

Example: Sorting Person Objects by Age

import java.util.*;
class Person implements Comparable<Person> {
    private String name;
    private int age;
    // Constructor
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    // Getter methods
    public String getName() {
        return name;
    }
    public int getAge() {
        return age;
    }
    // Implementing compareTo to compare by age
    @Override
    public int compareTo(Person other) {
        return Integer.compare(this.age, other.age); // Compare ages
    }
    // toString() method for easy output
    @Override
    public String toString() {
        return name + " (" + age + ")";
    }
    public static void main(String[] args) {
        // Create a List of Person objects
        List<Person> people = new ArrayList<>();
        people.add(new Person("Alice", 30));
        people.add(new Person("Bob", 25));
        people.add(new Person("Charlie", 35));
        people.add(new Person("David", 28));
        // Sort the list using compareTo() (which compares by age)
        Collections.sort(people);
        // Output the sorted list
        System.out.println("Sorted by age:");
        for (Person person: people) {
            System.out.println(person);
        }
    }
}

Explanation of the Example:

Person class: The class Person implements the Comparable<Person> interface, which means we must define the compareTo() method.

compareTo() method:

We evaluate Person objects based on their age by utilizing Integer.compare(this.age, other.age). 

Integer.compare(a, b) offers a more reliable method for comparing two integers, yielding: 

  • 0 if a equals b, 
  • A negative integer if a is smaller than b, and 
  • A positive integer if a exceeds b. 

Sorting

We generate a List<Person> and include multiple Person objects. 

We utilize Collections.sort(people) to arrange the list, and Java will invoke the compareTo() method to establish the sequence of the elements in the list according to their age. 

toString() method: We customize the toString() function to deliver a unique string format for every Person, simplifying the process of printing the object. 

Output:

Sorted by age:
Bob (25)
David (28)
Alice (30)
Charlie (35)

compareTo() vs Comparator

Comparable

Comparator

Comparable is an interface in Java.

Comparator is a functional interface in Java.

Comparable provides a compareTo() method to sort objects.

The comparator provides a compare() method to sort objects.

Comparable is a part of the Java.lang package.

Comparator is a part of the java.util package.

Comparable can be used for natural or default ordering.

A comparator can be used for custom ordering.

Comparable provides a single sorting sequence. Ex: Sort either by id or name

The comparator provides multiple sorting sequences. Ex. Sort by both id and name.

Comparable modifies the class that implements it.

The comparator doesn't modify any class.

CompareTo(): 

class Person implements Comparable<Person> {
    private String name;
    private int age;
    // Constructor
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    @Override
    public int compareTo(Person other) {
        return Integer.compare(this.age, other.age); // Compare based on age
    }
    @Override
    public String toString() {
        return name + " (" + age + ")";
    }
    public static void main(String[] args) {
        List<Person> people = Arrays.asList(
            new Person("Alice", 30),
            new Person("Bob", 25),
            new Person("Charlie", 35)
        );
        Collections.sort(people); // Uses compareTo() to sort by age
        System.out.println(people); // [Bob (25), Alice (30), Charlie (35)]
    }
}

Comparator:

import java.util.*;
class Person {
    private String name;
    private int age;
    // Constructor
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public int getAge() {
        return age;
    }
    @Override
    public String toString() {
        return name + " (" + age + ")";
    }
    public static void main(String[] args) {
        List<Person> people = Arrays.asList(
            new Person("Alice", 30),
            new Person("Bob", 25),
            new Person("Charlie", 35)
        );
        // Using Comparator to sort by name
        people.sort(new Comparator<Person>() {
            @Override
            public int compare(Person p1, Person p2) {
                return p1.getName().compareTo(p2.getName()); // Sort by name alphabetically
            }
        });
        System.out.println(people); // [Alice (30), Bob (25), Charlie (35)]
    }
}

Handling Null and Edge Cases

When utilizing the compareTo() method or Comparator in Java, managing null values and edge cases is essential for maintaining robustness and avoiding errors. Here are several recommended methods for managing these situations: 

Handling Null Values

Null values can be challenging when comparing objects since they lack a natural order. To prevent NullPointerException, it's essential to explicitly manage null values in your comparison logic. 

Handling Null in compareTo()

When creating the compareTo() method within the Comparable interface, it's crucial to think about how to handle scenarios where one of the objects being compared is null. Typically, you cannot invoke methods on null, so it is essential to manage it correctly.

Typical Approach:

  • If the calling object (this) is null, it should be regarded as either greater or lesser than the other object, based on the context. 
  • Alternatively, if the argument (other) is null, you might regard the argument as "less" than the invoking object. 

Example:

class Person implements Comparable<Person> {
    private String name;
    private Integer age;
    // Constructor
    public Person(String name, Integer age) {
        this.name = name;
        this.age = age;
    }
    // Overriding compareTo() to compare by age, handling null
    @Override
    public int compareTo(Person other) {
        if (other == null) {
            return 1;  // Consider this object greater if the other is null
        }
        // Null check for the 'age' field itself
        if (this.age == null && other.age == null) {
            return 0;  // Both null, they are equal
        }
        if (this.age == null) {
            return -1;  // This object is less because the age is null
        }
        if (other.age == null) {
            return 1;   // Other object is less because the age is null
        }
        return Integer.compare(this.age, other.age);  // Normal comparison
    }
    @Override
    public String toString() {
        return name + " (" + age + ")";
    }
    public static void main(String[] args) {
        Person p1 = new Person("Alice", 30);
        Person p2 = new Person("Bob", null);
        Person p3 = new Person("Charlie", 25);
        List<Person> people = Arrays.asList(p1, p2, p3);
        Collections.sort(people);
        System.out.println(people);  // Sorting with null handling
    }
}

Dealing with Null in Comparator

When utilizing a Comparator, you can directly manage null values in the comparison logic within the compare() method.

Typical Approach:

You can utilize Comparator.nullsFirst() or Comparator.nullsLast() from the Comparator utility class to manage null values reliably.

Example with Comparator:

import java.util.*;
class Person {
    private String name;
    private Integer age;
    // Constructor
    public Person(String name, Integer age) {
        this.name = name;
        this.age = age;
    }
    public Integer getAge() {
        return age;
    }
    @Override
    public String toString() {
        return name + " (" + age + ")";
    }
    public static void main(String[] args) {
        Person p1 = new Person("Alice", 30);
        Person p2 = new Person("Bob", null);
        Person p3 = new Person("Charlie", 25);
        List<Person> people = Arrays.asList(p1, p2, p3);
        // Comparator with null handling: nullsLast sorts nulls at the end
        people.sort(Comparator.comparing(Person::getAge, Comparator.nullsLast(Integer::compareTo)));
        System.out.println(people);  // Sorting with null handling
    }
}

Edge Cases to Handle

Case 1: Equal Objects

When two items are identical, the compareTo() function is expected to return 0. Make sure this situation is addressed properly by your compareTo() or Comparator method. 

Example:

@Override
public int compareTo(Person other) {
    if (this.age == null && other.age == null) {
        return 0;  // Both null ages are considered equal
    }
    return Integer.compare(this.age, other.age);  // If ages are the same, return 0
}

Case 2: Sorting in Reverse Order

At times, you may prefer to arrange in reverse order (from highest to lowest). You have the option to change the comparison logic or utilize Comparator.reversed(). 

Example:

people.sort(Comparator.comparing(Person::getAge).reversed());  // Sort in descending order

Case 3: Handling Comparable with Multiple Fields

If you possess items with various attributes (e.g., name and age), you might want to take both attributes into account for sorting. You can use compareTo() to compare based on the primary field and then revert to secondary fields in the event of ties. 

Example: Sorting by age, then by name:

@Override
public int compareTo(Person other) {
    int ageComparison = Integer.compare(this.age, other.age);
    if (ageComparison != 0) {
        return ageComparison;
    }
    return this.name.compareTo(other.name);  // If ages are the same, compare names
}

Common Interview Questions on compareTo()

1: What is the function of the compareTo() method in Java? 

A: The compareTo() function is included in the Comparable<T> interface, which serves to establish the natural ordering of objects. It enables the comparison of objects for the sake of sorting. 

2: What occurs if two objects are equivalent in compareTo()? 

A: If two items are deemed equivalent, the compareTo() method must return 0. This indicates that the items hold identical value when assessed with the established natural ordering principles. 

3: How does compareTo() differ from Comparator? 

A: The compareTo() method facilitates natural ordering and is specified in the Comparable<T> interface. It must be carried out within the class itself. 

A comparator is an outside interface utilized to establish personalized sorting behavior. It is helpful when you need to arrange objects in various manners or when you lack control over the class (i.e., you are unable to alter the class to include Comparable). 

4: What occurs when you mistakenly implement compareTo()? 

A: If compareTo() isn't implemented properly, it may lead to: 

  • Unreliable sorting can result from inconsistent outcomes. 
  • If the items being compared are of different types, it may result in a ClassCastException. 
  • If the compareTo() logic is incorrect, the objects might not be arranged in the intended order, potentially causing errors in the program. 

5: What is the definition of compareTo()? 

A: The compareTo() function is required to follow this contract: 

  • Reflexive
  • Transitive
  • Antisymmetric
  • Consistent with equals()

Practice Exercise Suggestion

Exercise 1: Implement compareTo() to sort students by marks.

To sort students by marks using compareTo(), you must define a Student class and implement the Comparable<Student> interface. Next, implement the compareTo() method to evaluate students according to their scores. 

Here’s a detailed implementation process: 

  • Design the Student class with properties: name (String) and marks (int). 
  • In the Student class, implement the Comparable<Student> interface. 
  • Implement the compareTo() method to evaluate the students based on their marks (in ascending order, by default). 
  • Arrange the students utilizing Collections.sort() or Arrays.sort(). 

Code Implementation:

import java.util.*;
public class Student implements Comparable<Student> {
    private String name;
    private int marks;
    // Constructor to initialize name and marks
    public Student(String name, int marks) {
        this.name = name;
        this.marks = marks;
    }
    // Getter methods for name and marks
    public String getName() {
        return name;
    }
    public int getMarks() {
        return marks;
    }
    // Implement compareTo to compare students by marks
    @Override
    public int compareTo(Student other) {
        // Compare by marks in ascending order
        return Integer.compare(this.marks, other.marks);
    }
    // Override toString method for better display
    @Override
    public String toString() {
        return name + " (" + marks + " marks)";
    }
    // Main method to test sorting of students
    public static void main(String[] args) {
        // Create a list of students
        List<Student> students = Arrays.asList(
            new Student("Alice", 85),
            new Student("Bob", 92),
            new Student("Charlie", 78),
            new Student("David", 95)
        );
        // Sort the students by marks in ascending order
        Collections.sort(students);
        // Print the sorted list of students
        System.out.println("Sorted students by marks:");
        for (Student student : students) {
            System.out.println(student);
        }
    }
}

Explanation:

Attributes:

name: The name of the student.

marks: The marks obtained by the student.

compareTo() Method:

The compareTo() function evaluates students according to their scores. 

It Returns: 

  • A negative value if the grades of the calling student are lower than those of the other student. 
  • If both students receive the same score, the result is zero. 
  • A positive number if the marks of the calling student exceed those of the other student. 

Sorting: 

  • We utilize Collections.sort() to arrange the list of students. As the Student class implements Comparable<Student>, the compareTo() method will automatically be invoked during sorting. 

Output

The students' list will be organized by their grades in increasing order (standard function of compareTo()). 

Sorted students by marks:
Charlie (78 marks)
Alice (85 marks)
Bob (92 marks)
David (95 marks)

Exercise 2: Modify compareTo() to sort employees by experience.

To change the compareTo() method for sorting employees based on experience, you must create an Employee class containing pertinent attributes (like name and experience), implement the Comparable<Employee> interface, and override the compareTo() method to evaluate employees according to their experience. 

Here’s how you can alter it: 

  • Establish the Employee class featuring attributes such as name (String) and experience (int). 
  • Add Comparable<Employee> to the Employee class. 
  • Modify the compareTo() method to compare employees according to their experience in either ascending or descending order, depending on your choice. 
  • Arrange employees by utilizing Collections.sort(). 

Code Implementation:

import java.util.*;
public class Employee implements Comparable<Employee> {
    private String name;
    private int experience;  // Experience in years
    // Constructor to initialize name and experience
    public Employee(String name, int experience) {
        this.name = name;
        this.experience = experience;
    }
    // Getter methods for name and experience
    public String getName() {
        return name;
    }
    public int getExperience() {
        return experience;
    }
    // Implement compareTo to compare employees by experience
    @Override
    public int compareTo(Employee other) {
        // Compare by experience in ascending order
        return Integer.compare(this.experience, other.experience);
    }
    // Override toString method for better display
    @Override
    public String toString() {
        return name + " (" + experience + " years experience)";
    }
    // Main method to test sorting of employees
    public static void main(String[] args) {
        // Create a list of employees
        List<Employee> employees = Arrays.asList(
            new Employee("Alice", 5),
            new Employee("Bob", 10),
            new Employee("Charlie", 2),
            new Employee("David", 7)
        );
        // Sort the employees by experience in ascending order
        Collections.sort(employees);
        // Print the sorted list of employees
        System.out.println("Sorted employees by experience:");
        for (Employee employee : employees) {
            System.out.println(employee);
        }
    }
}

Explanation:

Attributes:

name: The name of the employee.

experience: The number of years of experience the employee has.

compareTo() Method:

This method compares employees based on their experience.

It returns:

  • A negative number if the calling employee's experience is less than the other employee’s experience.
  • Zero if both employees have the same experience.
  • A positive number if the calling employee's experience is greater than the other employee’s experience.

Sorting:

Collections.sort() is used to sort the list of employees. Since Employee implements Comparable<Employee>, the compareTo() method is called during the sorting process to order employees by experience.

Output:

The employees will be sorted by their experience in ascending order.

Sorted employees by experience:
Charlie (2 years experience)
Alice (5 years experience)
David (7 years experience)
Bob (10 years experience)

Exercise 3: Write a Comparator to sort products by price in descending order.

To arrange products in descending order by price utilizing a Comparator, you must first establish a Product class, and then either create an independent Comparator class or apply a lambda expression for sorting by price in descending order. 

Steps:

  • Develop a Product class that includes characteristics such as name (String) and price (double). 
  • Design a Comparator to evaluate products based on their prices in decreasing order. 
  • Arrange items using Collections.sort() along with the Comparator. 

Code Implementation:

import java.util.*;
// Product class with name and price attributes
class Product {
    private String name;
    private double price;
    // Constructor to initialize name and price
    public Product(String name, double price) {
        this.name = name;
        this.price = price;
    }
    // Getter methods for name and price
    public String getName() {
        return name;
    }
    public double getPrice() {
        return price;
    }
    // Override toString method for better display
    @Override
    public String toString() {
        return name + " ($" + price + ")";
    }
}
// Comparator to sort products by price in descending order
class PriceDescendingComparator implements Comparator<Product> {
    @Override
    public int compare(Product p1, Product p2) {
        // Compare prices in descending order
        return Double.compare(p2.getPrice(), p1.getPrice());  // Reverse the order for descending
    }
}
public class Main {
    public static void main(String[] args) {
        // Create a list of products
        List<Product> products = Arrays.asList(
            new Product("Laptop", 1200.99),
            new Product("Smartphone", 799.49),
            new Product("Headphones", 199.99),
            new Product("Tablet", 399.99)
        );
        // Sort products by price in descending order using the Comparator
        Collections.sort(products, new PriceDescendingComparator());
        // Print the sorted list of products
        System.out.println("Products sorted by price (descending):");
        for (Product product : products) {
            System.out.println(product);
        }
    }
}

Explanation:

Product Class:

  • The Product class contains two attributes: name (the product's name) and price (the product's cost). 
  • The methods getName() and getPrice() are utilized to retrieve these attributes. 
  • The toString() method is redefined for improved presentation of product details. 

PriceDescendingComparator Class: 

  • This is a tailored comparator that implements Comparator<Product>. 
  • The compare() method evaluates two Product objects according to their price, arranging them in descending order. 
  • We utilize Double.compare(p2.getPrice(), p1.getPrice()) since compareTo for Double naturally sorts in ascending order, thus reversing the sequence results in descending sorting. 

Sorting

The method Collections.sort() is utilized to arrange the list of products in order. It accepts the list and the comparator (PriceDescendingComparator) as parameters. 

Output:

Products will be sorted by their price in descending order

Products sorted by price (descending):
Laptop ($1200.99)
Smartphone ($799.49)
Tablet ($399.99)
Headphones ($199.99)

Conclusion

The CompareTo in Java is an effective method for evaluating strings or Integer instances. It enables developers to establish the lexicographic or numerical sequence of two values. By grasping its behavior and usage, programmers can efficiently arrange and organize data according to certain criteria. 

It offers an easy method to apply comparison logic and facilitate informed decision-making in Java programming. You can explore courses and tutorials at upGrad to understand what compare() is in Java and how to utilize it. 

upGrad’s courses offer expert training in Java programming, focusing on the abs() method, performance optimization, and best practices. Gain hands-on experience in handling numerical computations, managing absolute values efficiently, and building high-performance Java applications.

Below are some relevant upGrad courses:

You can also get personalized career counseling with upGrad to guide your career path, or visit your nearest upGrad center and start hands-on training today! 

Similar Reads:

FAQs

1. What is the purpose of the compareTo method in Java?

In Java, the compareTo method serves to compare two objects of identical type and establish their relative sequence, returning a negative integer when the current object is lesser than the compared one, zero if they are equivalent, and a positive integer if the current object exceeds the compared object; effectively establishing the "natural order" for object comparison within a class. 

2. Which classes in Java implement the compareTo method?

In Java, the compareTo method belongs to the Comparable interface, which is implemented by several core Java classes such as String, Integer, Double, and Character. This implementation means these classes possess a built-in compareTo method, enabling natural ordering comparisons among objects of that type.

3. How does the compareTo method determine the order of objects?

The compareTo() method accepts another object of the same type as an argument and returns an integer that signifies the relative ordering of the two objects. The potential return values include: A negative integer if the current object is smaller than the argument object. 

4. What is the return value of the compareTo method when two strings are equal?

When two strings match, the compareTo method yields a result of 0. The compareTo method assesses strings lexicographically, and if they match, it signifies equality by returning 0. A positive number is returned when the first string is "greater than" the second, and a negative number when the first string is "less than" the second.

5. How does the compareTo method handle case sensitivity when comparing strings?

The compareToIgnoreCase() function compares two strings in a lexicographical manner, disregarding differences between uppercase and lowercase characters. The comparison relies on the Unicode value of every character in the string after being changed to lowercase. The function gives back 0 if the string matches the other string, disregarding case variations. 

6. Can the compareTo method be used to compare null values?

The compareTo() method in Java will throw a NullPointerException when attempting to compare an object with a null object. 

7. How does the compareTo method handle leading and trailing spaces in strings?

Evaluates two Strings to determine if one precedes or follows the other, or if they are identical. The strings are examined character by character, utilizing the ASCII values of the characters. This indicates that, for instance, 'a' is positioned before 'b' but after 'A'.

8. How does the compareTo method differ from the equals method in Java?

compareTo: Evaluates two strings in lexicographic order. equals: Checks if this string is equal to the given object. CompareTo assesses two strings based on their characters (at matching indices) and returns an integer that can be positive or negative based on the comparison. 

9. Can the compareTo method be overridden in custom classes?

When a class implements Comparable, it overrides the compareTo() method to define how instances of that class should be compared. The method yields: — A negative integer if the current object is smaller than the specified object. — Zero if the current object matches the specified object. 

10. What is the significance of implementing the Comparable interface in Java?

In Java, by implementing the Comparable interface, a class indicates that it establishes a natural order for its instances, enabling direct sorting using methods such as Collections.sort() without needing an additional comparator, effectively determining how instances of that class ought to be compared during sorting. 

11. How does the compareTo method facilitate sorting in Java collections?

The compareTo() function in Java evaluates objects and establishes their comparative sequence. It provides an integer result for the comparison. It is frequently utilized for arranging and organizing items. 

12. Can the compareTo method be used for case-insensitive comparisons?

CompareTo and Compare(String, String) functions. They each carry out a case-sensitive comparison.

image

Take the Free Quiz on Java

Answer quick questions and assess your Java knowledge

right-top-arrow
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Explore Our Free Software Tutorials

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918068792934

Disclaimer

1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.

2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.