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
- Java | Collectors maxBy(Comparator comparator) with Examples
- Stream sorted (Comparator comparator) method in Java
- Java | Collectors minBy(Comparator comparator) with Examples
- Find Unique pair in an array with pairs of numbers
- Comparable vs Comparator in Java
- Comparator comparingInt() in Java with examples
- PriorityBlockingQueue comparator() method in Java
- Comparator Interface in Java with Examples
- TreeSet comparator() Method in Java
- PriorityQueue comparator() Method in Java
- Comparator nullsLast() method in Java with examples
- Comparator reversed() method in Java with examples
- Comparator nullsFirst() method in Java with examples
- TreeMap comparator() method in Java with Examples
- Comparator thenComparingDouble() 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.