按升序对整个2d数组进行排序 [英] Sorting through entire 2d array in ascending order

查看:92
本文介绍了按升序对整个2d数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 Arrays.sort()以升序对2d数组进行排序.

I want to sort a 2d array in ascending order using Arrays.sort().

例如,我有这个数组:

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

排序后,输出应为:

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

像这样编写代码,但是它按行排序:

Wrote code like this, but it sorts by rows:

package domain;

import java.util.Arrays;

public class Exercise {
    private int[][] matrix = {
            {34, 2, 15, 12, 56},
            {3, 67, 6, 21, 9},
            {22, 5, 18, 65, 10},
            {52, 36, 112, 90, 0},
            {19, 48, 73, 16, 88}};

    // Method that displays the array
    public void DisplayArray() {
        for (int[] row : matrix) {
            System.out.println(Arrays.toString(row));
        }
    }

    public void Sorting() {
        for (int[] row : matrix) {
            Arrays.sort(row);
        }
    }
}

推荐答案

使用流,可以将2D数组转换为整数流,然后将其重新收集为2D数组:

Using streams, it is possible to convert the 2D array into a stream of integers and then recollect it to 2D array:

public static int[][] sort2D(int[][] arr) {
    int rows = arr.length;
    int cols = arr[0].length;
    int[] row = {0};
    
    return Arrays.stream(arr)
                 .flatMapToInt(Arrays::stream)
                 .sorted()
                 .boxed()
                 .collect(Collectors.groupingBy(x -> row[0]++ / cols))
                 .values()
                 .stream()
                 .map(r -> r.stream().mapToInt(Integer::intValue).toArray())
                 .toArray(int[][]::new);
}

测试

int[][] arr = {
  {9, 7, 5, 4},
  {3, 12, 11, 8},
  {6, 1, 2, 10}
};
int[][] sorted = sort2D(arr);
Arrays.stream(sorted)
      .map(Arrays::toString)
      .forEach(System.out::println);

输出

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

更新
使用方法 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆