Home > Java > javaTutorial > How to Sort a 2D Array in Java by the Values in the First Column?

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

Mary-Kate Olsen
Release: 2024-11-11 21:33:03
Original
563 people have browsed it

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

Sorting 2D Array based on First Column Values using Java Arrays.sort

In Java, sorting a 2D array based on the values of a specific column can be achieved using the overloaded Arrays.sort(T[] a, Comparator c) method that accepts a Comparator as its second argument.

Consider the following example, where we have a 2D array myArr containing pairs of doubles:

double[][] myArr = new double[mySize][2];
// populate myArr with data
Copy after login

To sort this array based on the first column values, we can use the Comparator interface to define a custom comparison rule:

java.util.Comparator<double[]> comparator = new java.util.Comparator<double[]>() {
    public int compare(double[] a, double[] b) {
        return Double.compare(a[0], b[0]);
    }
};
Copy after login

We can then pass this Comparator to the Arrays.sort method:

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

Alternatively, in Java 8 or later, we can use a lambda function instead of the anonymous inner class for the Comparator:

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

After sorting, the myArr will be sorted based on the values in the first column. The result will be:

[
  {1.0, 5.0},
  {12.0, 100.6},
  {12.1, 0.85},
  {13.0, 1.55}
]
Copy after login

The above is the detailed content of How to Sort a 2D Array in Java by the Values in the First Column?. 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