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} }
Recommended: Please try your approach on {IDE} first, before moving on to the solution.
Method 1: Using Comparable Interface
import java.io.*;
import java.util.*;
class Triplet implements Comparable<Triplet> {
int x;
int y;
int z;
public Triplet(int x,int y,int z){
this.x = x;
this.y = y;
this.z = z;
}
public String toString() {
return "(" + x + "," + y + "," + z + ")";
}
// Overridden method to compare
// values of the last element.
public int compareTo(Triplet a){
return this.z - a.z;
}
}
class GFG {
public static void main (String[] args) {
int n = 4;
Triplet arr[] = new Triplet[n];
arr[0] = new Triplet(1, 2, 3);
arr[1] = new Triplet(2, 2, 4);
arr[2] = new Triplet(5, 6, 1);
arr[3] = new Triplet(10, 2, 10);
// Sorting the array
Arrays.sort(arr);
// printing the
// Triplet array
print(arr);
}
public static void print(Triplet[] arr){
for(int i = 0;i < arr.length;i++){
System.out.println(arr[i]);
}
}
}
Output:
(5,6,1) (1,2,3) (2,2,4) (10,2,10)Method 2: Using Comparator Interface
import java.io.*;
import java.util.*;
class Triplet {
int x;
int y;
int z;
public Triplet(int x,int y,int z){
this.x = x;
this.y = y;
this.z = z;
}
public String toString() {
return "(" + x + "," + y + "," + z + ")";
}
}
class Compare implements Comparator<Triplet>{
// Overridden compare method to
// compare objects for sorting.
public int compare(Triplet a,Triplet b){
return a.z - b.z;
}
}
class GFG {
public static void main (String[] args) {
int n = 4;
Triplet arr[] = new Triplet[n];
arr[0] = new Triplet(10, 20, 30);
arr[1] = new Triplet(40, -1, 2);
arr[2] = new Triplet(30, 18, -1);
arr[3] = new Triplet(50, 10, 50);
// Sorting the array by passing
// Compare object
Arrays.sort(arr, new Compare());
// printing the Triplet array
print(arr);
}
public static void print(Triplet[] arr){
for(int i = 0;i < arr.length;i++){
System.out.println(arr[i]);
}
}
}
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.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4