Home  >  Article  >  Java  >  How to Sort a 2D Array by its First Column in Java?

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

DDD
DDDOriginal
2024-11-12 09:24:02961browse

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

Sorting a 2D Array by the First Column Using Java's Arrays.sort

In Java, sorting a 2D array based on the values of the first column can be achieved using the overloaded Arrays.sort method that takes a Comparator as a second argument. This Comparator allows you to specify a custom comparison logic for sorting the array elements.

To sort a 2D array using the first column values, you can follow these steps:

Create a Comparator implementation that compares the first elements of the subarrays. This can be done using the Double.compare method for comparing double values:

Comparator<double[]> comparator = (a, b) -> Double.compare(a[0], b[0]);

Call the Arrays.sort method with the array and the Comparator as arguments:

Arrays.sort(array, comparator);

Alternatively, if you're using Java 8 or higher, you can use a lambda function to simplify the Comparator:

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

Example:

Consider the following 2D array myArr:

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

After sorting myArr using the approach described above, it will be sorted based on the first column values:

1      5
12     100.6
12.1   .85
13     1.55

The above is the detailed content of How to Sort a 2D Array by its 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