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 minBy(Comparator comparator) with Examples
- Stream sorted (Comparator comparator) method in Java
- Java | Collectors maxBy(Comparator comparator) with Examples
- Find Unique pair in an array with pairs of numbers
- Comparable vs Comparator in Java
- TreeSet comparator() Method in Java
- PriorityQueue comparator() Method in Java
- PriorityBlockingQueue comparator() method in Java
- Comparator Interface in Java with Examples
- SortedMap comparator() method in Java with Examples
- TreeMap comparator() method in Java with Examples
- ConcurrentSkipListSet comparator() method in Java with Examples
- Java Program to Count Inversions in an array | Set 1 (Using Merge Sort)
- Sorting Vector of Pairs in C++ | Set 1 (Sort by first and second)
- Sorting Vector of Pairs in C++ | Set 2 (Sort in descending order by first and second)
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.