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 Java and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.
- Stream sorted (Comparator comparator) method in Java
- Java | Collectors maxBy(Comparator comparator) with Examples
- Java | Collectors minBy(Comparator comparator) with Examples
- Sort an Array of dates in ascending order using Custom Comparator
- Count number of pairs with the given Comparator
- Store duplicate keys-values pair and sort the key-value pair by key
- Comparator Interface in Java with Examples
- Comparable vs Comparator in Java
- TreeSet comparator() Method in Java
- PriorityQueue comparator() Method in Java
- PriorityBlockingQueue comparator() method in Java
- TreeMap comparator() method in Java with Examples
- SortedMap comparator() method in Java with Examples
- ConcurrentSkipListSet comparator() method in Java with Examples
- Comparator nullsFirst() method in Java with examples
- Comparator comparingInt() in Java with examples
- Comparator nullsLast() method in Java with examples
- Comparator thenComparingInt() method in Java with examples
- Comparator reverseOrder() method in Java with examples
- Comparator reversed() 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 firstname.lastname@example.org. 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.