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
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Sort an Array of dates in ascending order using Custom Comparator
- Stream sorted (Comparator comparator) method in Java
- Java | Collectors minBy(Comparator comparator) with Examples
- Java | Collectors maxBy(Comparator comparator) with Examples
- Count number of pairs with the given Comparator
- Find Unique pair in an array with pairs of numbers
- Find the Kth pair in ordered list of all possible sorted pairs of the Array
- Store duplicate keys-values pair and sort the key-value pair by key
- Number of indices pair such that element pair sum from first Array is greater than second Array
- Comparable vs Comparator in Java
- PriorityQueue comparator() Method in Java
- TreeSet comparator() Method in Java
- PriorityBlockingQueue comparator() method in Java
- Comparator Interface in Java with Examples
- Comparator comparingInt() in Java with examples
- Comparator nullsFirst() method in Java with examples
- Comparator thenComparingDouble() method in Java with examples
- Comparator nullsLast() method in Java with examples
- Comparator thenComparingInt() method in Java with examples
- Comparator comparingLong() 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.