- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sort an Array of Triplet using Java Comparable and Comparator
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.
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.
Program to sort Array of Triplet using Comparator
Comparator
As the name suggests it 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 sorting operation to methods like ‘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);
Working of code
Create a class and its constructor named ‘Cart’. Inside it, declare three variables.
In the main method, create a comparator and inside it override its method ‘compare()’ that will contain logic for sorting.
Now, we will create an array of triplet and sort them using inbuilt method ‘Array.sort()’
Example
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
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
Program to sort Array of Triplet using Comparable
Comparable
This 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);
Working of code
Create a class that implements Comparable interface. Then define its constructor and inside it, declare three variables.
Define your logic of sorting inside the method ‘compareTo()’.
Now, in the main method, we will create an array of triplet and sort them using inbuilt method ‘Array.sort()’
Example
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); } } }
Output
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
Conclusion
Both interfaces Comparable and Comparator are used to sort elements of a given list or objects but, the comparable interface modifies the original class whereas comparator does not. In this article, we learned how we can sort an array of triplet using these interfaces.