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
Release: 2024-11-10 18:46:02
Original
334 people have browsed it

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
Copy after login
1      5
13     1.55
12     100.6
12.1   .85
Copy after login

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]);
    }
};
Copy after login

Then, we can sort the array using this comparator:

java.util.Arrays.sort(myArr, comparator);
Copy after login

Result:

1      5
12     100.6
12.1   .85
13     1.55
Copy after login

JAVA-8:

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

Arrays.sort(myArr, Comparator.comparingDouble(o -> o[0]));
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template