Home > Java > javaTutorial > body text

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

Patricia Arquette
Release: 2024-11-13 01:40:02
Original
903 people have browsed it

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

Sorting a 2D Array Using Arrays.sort

Sorting a multidimensional array can be a complex task. However, using Java's Arrays.sort method, it is possible to achieve this efficiently.

Specifically, the solution involves using the overloaded Arrays#Sort(T[] a, Comparator c) method, which takes a Comparator as its second argument. A comparator is an object that defines how objects are compared. In this case, we want to compare the values of the first element in each subarray.

To implement this, create a comparator that implements the java.util.Comparator interface and overrides its compare() method. This method should compare the first elements of the two arrays and return -1, 0, or 1 depending on the order they should appear.

For instance, consider the following 2D array:

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

To sort this array in ascending order based on the values of the first element in each subarray, use the following code:

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

This will produce the following sorted array:

[
  {1, 5},
  {12, 100.6},
  {12.1, .85},
  {13, 1.55}
]
Copy after login

In Java 8 and later, you can use lambdas to simplify the comparator:

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

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