How to sort 2d array in java using stream api

How to sort 2d array in java using stream api

To sort a 2D array in Java using the Stream API, you can first convert the array to a Stream of rows, and then use the sorted method to sort the rows based on a specific column.

Here's an example of how you can do this:

refer‮al:ot ‬utturi.com
int[][] array = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};

array = Arrays.stream(array)
    .sorted((row1, row2) -> Integer.compare(row1[1], row2[1]))
    .toArray(int[][]::new);

System.out.println(Arrays.deepToString(array));

This code will sort the 2D array array based on the values in the second column (index 1), and print the sorted array to the console. The output will be:

[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

You can customize the sorting function to sort the rows based on different criteria, such as the values in a different column or the combination of multiple columns. You can also use the reverseOrder method of the Comparator class to reverse the order of the sort.

For example, to sort the rows in descending order based on the values in the third column (index 2), you can use the following code:

int[][] array = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};

array = Arrays.stream(array)
    .sorted((row1, row2) -> Integer.compare(row2[2], row1[2]))
    .toArray(int[][]::new);

System.out.println(Arrays.deepToString(array));
Created Time:2017-11-01 20:42:48  Author:lautturi