# Sort an array of pairs using Java Pair and Comparator

• Difficulty Level : Basic
• Last Updated : 01 Aug, 2022

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 first element.
• Sort the array according to the first 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.io.*;` `import` `java.util.*;`   `// User defined Pair class` `class` `Pair {` `    ``int` `x;` `    ``int` `y;`   `    ``// Constructor` `    ``public` `Pair(``int` `x, ``int` `y)` `    ``{` `        ``this``.x = x;` `        ``this``.y = y;` `    ``}` `}`   `// class to define user defined conparator` `class` `Compare {`   `    ``static` `void` `compare(Pair arr[], ``int` `n)` `    ``{` `        ``// Comparator to sort the pair according to second` `        ``// element` `        ``Arrays.sort(arr, ``new` `Comparator& lt; Pair& gt; () {` `            ``@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.` `            ``}` `        ``});`   `        ``for` `(``int` `i = ``0``; i & lt; n; i++) {` `            ``System.out.print(arr[i].x + " "` `                             ``+ arr[i].y + " ");` `        ``}` `        ``System.out.println();` `    ``}` `}`   `// Main class` `class` `GFG {`   `    ``// Main driver method ` `    ``public` `static` `void` `main(String[] args)` `    ``{` `       ``// Reading input ` `        ``Scanner sc = ``new` `Scanner(System.in);`   `        ``// length of array` `        ``int` `n = ``5``;`   `        ``// Array of Pair` `        ``Pair arr[] = ``new` `Pair[n];`   `        ``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``);`   `        ``// Creating object of above class inside main method ` `        ``Compare obj = ``new` `Compare();`   `        ``obj.compare(arr, n);` `    ``}` `}`

Output:

`3 1 1 2 4 3 10 8 10 20`

My Personal Notes arrow_drop_up
Related Articles