"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 Double Array by the First Column in Java?

How to Sort a 2D Double Array by the First Column in Java?

Posted on 2025-03-12
Browse:723

How to Sort a 2D Double Array by the First Column in Java?

Sorting 2D Arrays Using Java's Arrays.sort()

Arrays.sort() is a versatile sorting function in Java that can be utilized for various data types, including 2D arrays. In this specific scenario, we aim to sort a 2D double array based on the values in the first column.

To achieve this without implementing a custom sorting algorithm, we can leverage the overloaded version of Arrays#Sort(T[] a, Comparator c). By providing a Comparator as the second argument, we can specify our own sorting criteria.

For the given array:

double[][] myArr = new double[mySize][2];
// Initial array contents
1      5
13     1.55
12     100.6
12.1   .85

We can create a comparator that compares the first elements of each row:

Comparator comparator = new Comparator() {
    @Override
    public int compare(double[] a, double[] b) {
        return Double.compare(a[0], b[0]);
    }
};

Then, we can sort the array using this comparator:

java.util.Arrays.sort(myArr, comparator);

Result:

1      5
12     100.6
12.1   .85
13     1.55

JAVA-8:

In Java 8 and later, we can simplify the comparator using a lambda expression:

Arrays.sort(myArr, Comparator.comparingDouble(o -> o[0]));
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