Home >Java >javaTutorial >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?

Linda Hamilton
Linda HamiltonOriginal
2024-11-10 18:46:02303browse

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<double[]> comparator = new Comparator<double[]>() {
    @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]));

The above is the detailed content of How to Sort a 2D Double Array by the First Column in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn