VOOZH about

URL: https://www.geeksforgeeks.org/java/sort-an-array-of-triplet-using-java-comparable-and-comparator/

⇱ Sort an Array of Triplet using Java Comparable and Comparator - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Sort an Array of Triplet using Java Comparable and Comparator

Last Updated : 23 Jul, 2025

Given an array of integer Triplet. you have to sort the array in ascending order with respect to the last element in the triplet.

Examples:

Input: { {1, 2, 3}, {2, 2, 4}, {5, 6, 1}, {10, 2, 10} }
Output: { {5, 6, 1}, {1, 2, 3}, {2, 2, 4}, {10, 2, 10} }

Input: { {10, 20, 30}, {40, -1, 2}, {30, 10, -1}, {50, 10, 50} }
Output: { {30, 18, -1}, {40, -1, 2}, {10, 20, 30}, {50, 10, 50} }

Method 1: Using Comparable Interface

  • In this method, we are going to implement the Comparable interface from java.lang Package in the Triplet class.
  • The Comparable interface contains the method compareTo to decide the order of the elements.
  • Override the compareTo method in the Triplet class.
  • Create an array of Triplet and populate the array.
  • Use the Arrays.sort() function to sort the array.

Output:

(5,6,1)
(1,2,3)
(2,2,4)
(10,2,10)

Method 2: Using Comparator Interface

  • In this method, we create a separate Compare class that implements Comparator Interface
  • The Comparable interface contains the method compared to order the elements.
  • Override the compare method in the Compare class.
  • Create an array of Triplet and populate the array.
  • Use the Arrays.sort() function to sort the array and pass an object of Compare class.

Output:

(30,18,-1)
(40,-1,2)
(10,20,30)
(50,10,50)

In this article, we sorted a user-defined triplet by using java comparable and comparator interface. Remember, the same can be implemented for any element in the triplet just by the change the variable name in the overridden class methods in the compareTo and compare.

Comment