Open In App

Sort an array of pairs using Java Arrays.sort() with custom Comparator

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

Given an array of pairs of integers. The task is to sort the array with respect to the second element of the pair.

Examples: 

Input: [(1, 2), (3, 5), (2, 6), (1, 7)]
Output: [(1, 2), (3, 5), (2, 6), (1, 7)]

Input: [(10, 20), (20, 30), (5, 6), (2, 5)]
Output: [(2, 5), (5, 6), (10, 20), (20, 30)]

Approach:  

  • Store the pairs in an array using a user-defined Pair class.
  • Override the comparator method to sort the array according to the second element.
  • Sort the array according to the second element.

Below is the implementation of the above approach:

Java




// Java code to sort the array
// according to second element
 
// Importing required classes
import java.util.Arrays;
import java.util.Comparator;
 
// User defined Pair class
class Pair {
    int x;
    int y;
 
    // Constructor
    public Pair(int x, int y) {
        this.x = x;
        this.y = y;
    }
 
      // Overriding toString method
    //       for beautiful printing of pairs
    @Override
    public String toString() {
        return "(" + x +
                ", " + y +
                ')';
    }
}
 
// class to define user defined comparator
class ArrayOfPairsSorter {
 
    static void sort(Pair[] arr) {
        Comparator<Pair> comparator = new Comparator<>() {
            @Override
            public int compare(Pair p1, Pair p2) {
                return p1.y
                        - p2.y; // To compare the first element
                                // just
                                // change the variable from p1.y
                                // - p2.y to p1.x-p2.x.
            }
        };
        Arrays.sort(arr, comparator);
    }
}
 
// Main class
class GFG {
 
    // Main driver method
    public static void main(String[] args) {
 
        // Array of 5 Pairs
        Pair[] arr = new Pair[5];
 
        arr[0] = new Pair(10, 20);
        arr[1] = new Pair(1, 2);
        arr[2] = new Pair(3, 1);
        arr[3] = new Pair(10, 8);
        arr[4] = new Pair(4, 3);
 
        ArrayOfPairsSorter.sort(arr);
        System.out.println(Arrays.toString(arr));
    }
}


Output
[(3, 1), (1, 2), (4, 3), (10, 8), (10, 20)]



Last Updated : 03 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads