"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Sort a 2D Array in Java Using Arrays.sort and Comparators?

How to Sort a 2D Array in Java Using Arrays.sort and Comparators?

Posted on 2025-02-07
Browse:118

How to Sort a 2D Array in Java Using Arrays.sort and Comparators?

Sorting 2D Arrays in Java Using Arrays.sort

One way to sort a 2D array based on the values of without implementing your own sorting algorithm is to use the overloaded Arrays#Sort(T[] a, Comparator c) method.

double[][] array = {
        {1, 5},
        {13, 1.55},
        {12, 100.6},
        {12.1, .85}
};

java.util.Arrays.sort(array, new java.util.Comparator() {
    public int compare(double[] a, double[] b) {
        return Double.compare(a[0], b[0]);
    }
});

This method takes a Comparator as its second argument, allowing you to define your own sorting criteria. In this case, the Comparator we've provided compares the first element of each double[] array and returns an integer indicating whether it's less than, greater than, or equal to 0.

Using Lambda Functions in Java 8

Java 8 introduces lambda functions, which provide a concise way to define Comparators. We can rewrite the previous code using a lambda function as follows:

Arrays.sort(array, Comparator.comparingDouble(o -> o[0]));

This lambda function takes a double[] array as its input and returns the value of the first element as a double. By sorting the array using this Comparator, we achieve the desired result.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3