Sorting Custom Object by Implementing Comparable Interface in Java


Java provides a variety of sorting algorithms and methods that can help us to sort arrays, lists or any collections. The comparable interface is an additional way that is useful when we want to sort custom objects by their natural ordering. For example, it sorts strings in dictionary order and numerics in numerical order. This interface is available in ‘java.lang’ package.

In this article, we will learn the use of Comparable Interface through examples. Also, we discuss a few methods and classes of Collection Interface that are going to help us in sorting of custom objects using comparable interface.

Sorting by implementing Comparable Interface

Syntax for Comparable Interface

class nameOfclass implements Comparable<nameOfclass>

Before jumping into the program let’s understand few classes and methods.

compareTo() method

The Comparable interface defines only a single method named ‘CompareTo’ that can be overridden in order to sort the collection of objects. It gives the power to compare the objects of a class to itself. It returns 0 when ‘this’ object is equal to passed object, a positive value if ‘this’ object is greater otherwise a negative value.

Syntax

compareTo( nameOfclass nameOfobject ); 

Collections.sort() method

The class ‘Collections’ of the Collection Interface provides a static method named ‘Collections.sort()’ that can sort elements of specified collections like ArrayList or LinkedList. It is available in ‘java.util’ package.

Syntax

Collections.sort( nameOfcollection );

Algorithm

  • Step 1 − We will begin with importing ‘java.util’ package so that we can use ‘sort()’ method in our program.

  • Step 2 − Create a class ‘Cart’ that implements Comparable Interface. Inside it, declare two variables and define a constructor of this class along with two parameters ‘item’ and ‘price’ of type string and integer respectively.

  • Step 3 − Moving further we will convert the data of object into string using ‘toString()’ method. Then, define ‘compareTo’ method along with an object of class ‘Cart’ as a parameter to compare ‘this’ object with newly created object.

  • Step 4 − Now, in the main() method, declare an object named ‘obj’ of class ‘Cart’ of collection type ArrayList and using in-built method named ‘add()’ store the details of object to the collection.

  • Step 5 − At the end, we will pass ‘obj’ as an argument to the method ‘Collections.sort()’ to perform sorting operation and using for each loop we print the result.

Example

import java.util.*;
public class Cart implements Comparable<Cart> {
   String item;
   double price;
   Cart(String item, int price) {
      // this keyword shows these variables belongs to constructor
      this.item = item; 
      this.price = price;
   }
   // method for converting object into string
   public String toString() {
      return "Item: " + item + ", " + "Price: " + price;
   }
   // overriding method
   public int compareTo(Cart comp) {
      if(this.price > comp.price) {
         return 1;
      } else {
         return -1;
      }
   }
   public static void main(String[] args) {
      // Declaring collection arraylist
      List<Cart> obj = new ArrayList<>();
      // Adding object to the collection
      obj.add(new Cart("Rice", 59));
      obj.add(new Cart("Milk", 60));
      obj.add(new Cart("Bread", 45));
      obj.add(new Cart("Peanut", 230));
      obj.add(new Cart("Butter", 55));
      System.out.println("The original Objects: ");
      // to print unsorted list of objects
      for(Cart print : obj) {
         System.out.println(print);	
      }
      Collections.sort(obj); 
      // Sorting the object
      System.out.println("The newly sorted Objects: ");
      // to print newly sorted list of objects
      for(Cart print : obj) {
         System.out.println(print);	
      }
   }
}

Output

The original Objects: 
Item: Rice, Price: 59.0
Item: Milk, Price: 60.0
Item: Bread, Price: 45.0
Item: Peanut, Price: 230.0
Item: Butter, Price: 55.0
The newly sorted Objects: 
Item: Bread, Price: 45.0
Item: Butter, Price: 55.0
Item: Rice, Price: 59.0
Item: Milk, Price: 60.0
Item: Peanut, Price: 230.0

Conclusion

In Java version 1.0, the comparable interface was first introduced and made available in ‘java.lang’ package. Generally, the classes, methods and interfaces defined in this package are by default available for our use therefore, it is not important to import before using. This article has explained implementation of the Comparable Interface and also we discovered the use of its inbuilt method ‘compareTo()’.

Updated on: 12-May-2023

378 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements