Home > Java > javaTutorial > How to Sort a 2D Array in Java Using Arrays.sort and Comparators?

How to Sort a 2D Array in Java Using Arrays.sort and Comparators?

Mary-Kate Olsen
Release: 2024-11-11 09:34:03
Original
204 people have browsed it

How to Sort a 2D Array in Java Using Arrays.sort and Comparators?

Sorting 2D Arrays in Java Using Arrays.sort

One way to sort a 2D array based on the values of without implementing your own sorting algorithm is to use the overloaded Arrays#Sort(T[] a, Comparator c) method.

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

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

This method takes a Comparator as its second argument, allowing you to define your own sorting criteria. In this case, the Comparator we've provided compares the first element of each double[] array and returns an integer indicating whether it's less than, greater than, or equal to 0.

Using Lambda Functions in Java 8

Java 8 introduces lambda functions, which provide a concise way to define Comparators. We can rewrite the previous code using a lambda function as follows:

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

This lambda function takes a double[] array as its input and returns the value of the first element as a double. By sorting the array using this Comparator, we achieve the desired result.

The above is the detailed content of How to Sort a 2D Array in Java Using Arrays.sort and Comparators?. 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