Sort an Array of Triplet Using Java Comparable and Comparator



In this article, we will create an array of triplet and try to sort them using the Comparable and Comparator interfaces. The term array of triplet means an array having three elements.

An Array is a linear data structure that is used to store group of elements with similar datatypes. It stores data in a sequential manner. Once we create an array we can't change its size i.e. it is of fixed length.

Sort an Array of Triplet using Comparator

As the name suggests, Comparator is used to compare something. In Java, the Comparator is an interface that is used to sort custom objects. We can write our own logic inside its inbuilt method named compare() to sort the specified objects. This method takes two objects as arguments and then returns an integer value. By this integer value, Comparator decides which object is greater.

Syntax

Comparator< TypeOfComparator > nameOfComparator = new Comparator< TypeOfComparator >() {
   compare( type object1, type object1 ) {
      // logic for comparison
   }
};  

The nameOfComparator passed for the sorting operation to the method Arrays.sort().

Arrays.sort()

It is a static method of class Arrays that takes an argument and sort its elements accordingly. This method can sort arrays of numeric datatypes like integers or doubles and even arrays of characters, string too.

Syntax

Arrays.sort(nameOfarray);

Example

In this example, create a comparator and inside it override its method compare() that will contain logic for sorting. Then, create an array of triplet and sort them using the built-in method Array.sort().

import java.util.*;
class Cart {
   String item;
   double price;
   int quant;
   Cart(String item, int price, int quant) { // Constructor
      this.item = item;
      this.price = price;
      this.quant = quant;
   }
}
public class AraySort {
   public static void main(String args[]) {
      // use of comparator interface
      Comparator<Cart> comp = new Comparator<Cart>() {
         // logic to sort
         public int compare(Cart i, Cart j) {
            if(i.quant > j.quant) {
               return 1;
            } else {
               return -1;
            }
         }
      };
      // creating triplet of array
      Cart[] obj = new Cart[3]; 
      obj[0] = new Cart("Rice", 59, 5);
      obj[1] = new Cart("Milk", 60, 2);
      obj[2] = new Cart("Bread", 45, 1);
      Arrays.sort(obj, comp); 
      // to sort
      System.out.println("Elements of the newly sorted array: ");
	   for(int i = 0; i < obj.length; i++) {
         System.out.println("Item: " + obj[i].item + ", " + "Price: " + obj[i].price + ", " + "Quantity: " + obj[i].quant);	
      }
	}
}

Output of the above code is as follows ?

Elements of the newly sorted array: 
Item: Bread, Price: 45.0, Quantity: 1
Item: Milk, Price: 60.0, Quantity: 2
Item: Rice, Price: 59.0, Quantity: 5

Sort Array of Triplet using Comparable

The Comparable interface 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.

Syntax

class nameOfclass implements Comparable<nameOfclass>

Here, class is the keyword that creates a Class and implements is the keyword that enables the use of features provided by an Interface.

compareTo()

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);

Example

The following Java program demonstrates how to sort array of triplet using Comparable interface. Here, create a class that implements Comparable interface. Define your logic of sorting inside its method compareTo(). Then, in the main method, create an array of triplet and use Array.sort() method to sort it.

import java.util.*;
public class Cart implements Comparable<Cart>{
   String item;
   double price;
   int quant;
   Cart(String item, int price, int quant) { 
      // Constructor
      this.item = item;
      this.price = price;
      this.quant = quant;
   }
   // to compare 
   public int compareTo(Cart comp) {
      if(this.quant > comp.quant) {
         return 1;
      } else {
         return -1;
      }
   }
   public static void main(String args[]) {
      // creating triplet of array
      Cart[] obj = new Cart[3];
      obj[0] = new Cart("Rice", 59, 5);
      obj[1] = new Cart("Milk", 60, 2);
      obj[2] = new Cart("Bread", 45, 1);
      Arrays.sort(obj); 
      // to sort
      System.out.println("Elements of the newly sorted array: ");
	   for(int i = 0; i < obj.length; i++) {
         System.out.println("Item: " + obj[i].item + ", " + "Price: " + obj[i].price + ", " + "Quantity: " + obj[i].quant);	
      }
	}
}

On running, it will display the following result ?

Elements of the newly sorted array: 
Item: Bread, Price: 45.0, Quantity: 1
Item: Milk, Price: 60.0, Quantity: 2
Item: Rice, Price: 59.0, Quantity: 5
Updated on: 2025-04-17T10:49:11+05:30

282 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements