Given an array of pairs of integers. The task is to sort the array with respect to second element of the pair.
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)]
- 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 above approach:
3 1 1 2 4 3 10 8 10 20
- Stream sorted (Comparator comparator) method in Java
- Java | Collectors maxBy(Comparator comparator) with Examples
- Java | Collectors minBy(Comparator comparator) with Examples
- Find Unique pair in an array with pairs of numbers
- Number of indices pair such that element pair sum from first Array is greater than second Array
- Comparable vs Comparator in Java
- Comparator Interface in Java with Examples
- Comparator comparingInt() in Java with examples
- TreeSet comparator() Method in Java
- PriorityBlockingQueue comparator() method in Java
- PriorityQueue comparator() Method in Java
- TreeMap comparator() method in Java with Examples
- Comparator nullsLast() method in Java with examples
- Comparator thenComparingDouble() method in Java with examples
- Comparator comparingDouble() method in Java with examples
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.