Open In App

Sort an array of pairs using Java Arrays.sort() with custom Comparator

Last Updated : 03 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array of pairs of integers. The task is to sort the array with respect to the second element of the pair.

Examples: 

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)]

Approach:  

  • Store the pairs in an array using a user-defined Pair class.
  • Override the comparator method to sort the array according to the second element.
  • Sort the array according to the second element.

Below is the implementation of the above approach:

Java




// Java code to sort the array
// according to second element
 
// Importing required classes
import java.util.Arrays;
import java.util.Comparator;
 
// User defined Pair class
class Pair {
    int x;
    int y;
 
    // Constructor
    public Pair(int x, int y) {
        this.x = x;
        this.y = y;
    }
 
      // Overriding toString method
    //       for beautiful printing of pairs
    @Override
    public String toString() {
        return "(" + x +
                ", " + y +
                ')';
    }
}
 
// class to define user defined comparator
class ArrayOfPairsSorter {
 
    static void sort(Pair[] arr) {
        Comparator<Pair> comparator = new Comparator<>() {
            @Override
            public int compare(Pair p1, Pair p2) {
                return p1.y
                        - p2.y; // To compare the first element
                                // just
                                // change the variable from p1.y
                                // - p2.y to p1.x-p2.x.
            }
        };
        Arrays.sort(arr, comparator);
    }
}
 
// Main class
class GFG {
 
    // Main driver method
    public static void main(String[] args) {
 
        // Array of 5 Pairs
        Pair[] arr = new Pair[5];
 
        arr[0] = new Pair(10, 20);
        arr[1] = new Pair(1, 2);
        arr[2] = new Pair(3, 1);
        arr[3] = new Pair(10, 8);
        arr[4] = new Pair(4, 3);
 
        ArrayOfPairsSorter.sort(arr);
        System.out.println(Arrays.toString(arr));
    }
}


Output
[(3, 1), (1, 2), (4, 3), (10, 8), (10, 20)]



Similar Reads

Stream sorted (Comparator comparator) method in Java
Stream sorted(Comparator comparator) returns a stream consisting of the elements of this stream, sorted according to the provided Comparator. For ordered streams, the sort method is stable but for unordered streams, no stability is guaranteed. It is a stateful intermediate operation i.e, it may incorporate state from previously seen elements when p
3 min read
Java | Collectors maxBy(Comparator comparator) with Examples
Collectors maxBy(Comparator&lt;? super T&gt; comparator) is used to find an element according to the comparator passed as the parameter. It returns a Collector that produces the maximal element according to a given Comparator, described as an Optional&lt;T&gt;. Syntax: public static &lt;T&gt; Collector&lt;T, ?, Optional&lt;T&gt;&gt; maxBy(Comparato
3 min read
Java | Collectors minBy(Comparator comparator) with Examples
Collectors minBy(Comparator&lt;? super T&gt; comparator) is used to find an element according to the comparator passed as the parameter. It returns a Collector that produces the minimal element according to a given Comparator, described as an Optional&lt;T&gt;. Syntax: public static &lt;T&gt; Collector&lt;T, ?, Optional&lt;T&gt;&gt; minBy(Comparato
4 min read
Sort an Array of dates in ascending order using Custom Comparator
Given an array arr[] of N dates in the form of "DD-MM-YYYY", the task is to sort these dates in ascending order. Examples: Input: arr[] = { "25-08-1996", "03-08-1970", "09-04-1994" } Output: 03-08-1970 09-04-1994 25-08-1996 Input: arr[] = { "03-08-1970", "09-04-2020", "19-04-2019""} Output: 03-08-1970 19-04-2019 09-04-2020 Approach: Create a Custom
6 min read
Sort and separate odd and even numbers in an Array using custom comparator
Given an array arr[], containing N elements, the task is to sort and separate odd and even numbers in an Array using a custom comparator. Example: Input: arr[] = { 5, 3, 2, 8, 7, 4, 6, 9, 1 }Output: 2 4 6 8 1 3 5 7 9 Input: arr[] = { 12, 15, 6, 2, 7, 13, 9, 4 }Output: 2 4 6 12 7 9 13 15 Approach: As we know std::sort() is used for sorting in increa
5 min read
How to Fix java.lang.ClassCastException in TreeSet By Using Custom Comparator in Java?
This error is thrown by TreeSet because TreeSet is used to store elements in sorted order and if the specified element cannot be compared with the elements currently in the set then TreeSet won't be able to store elements in sorted order and hence, TreeSet throws class cast exception. How to fix this error? By providing a custom Comparator in TreeS
4 min read
How to Implement a Custom Comparator for a LinkedHashSet in Java?
In Java, we cannot directly implement a custom comparator for a LinkedHashSet. But sometimes we need a requirement of custom comparator for example custom sorting. So, we can use some alternative approaches to fulfill the requirements. In this article, we will be using a class for creating the custom comparator and this class will implement the Com
3 min read
Custom Comparator for a Specific Element type in a PriorityQueue in Java
PriorityQueue in Java is a data structure that stores elements according to their specified natural order or comparison. By default, it uses a natural order, but we can also define customized comparisons to sort things out based on specific criteria. Custom Comparator in PriorityQueueA Custom Comparator in Java is an interface that defines a method
3 min read
Sort an Array of Triplet using Java Comparable and Comparator
Given an array of integer Triplet. you have to sort the array in ascending order with respect to the last element in the triplet. Examples: Input: { {1, 2, 3}, {2, 2, 4}, {5, 6, 1}, {10, 2, 10} } Output: { {5, 6, 1}, {1, 2, 3}, {2, 2, 4}, {10, 2, 10} } Input: { {10, 20, 30}, {40, -1, 2}, {30, 10, -1}, {50, 10, 50} } Output: { {30, 18, -1}, {40, -1,
3 min read
Sort an Array in Java using Comparator
A Comparator is an object that can be used to compare two objects and determine their order. You can use a Comparator to sort a list of objects in any order you choose, not just in ascending order. Examples:Array(Ascending Order): Input: arr = (4, 2, 5, 1, 3) Output: [1, 2, 3, 4, 5] Array(Descending Order): Input: arr = (4, 2, 5, 1, 3) Output: [5,
4 min read