如何将不同大小的子数组存储到一个二维数组中

huangapple go评论69阅读模式
英文:

How to store subarrays of different size into a single 2d array

问题

我正在尝试将不同大小的一维数组存储到二维数组中,然后根据子数组的和对二维数组进行排序。

英文:

I’m trying to store 1d array of different size into a 2d array and then sort the 2d array based on the sum of subarray.

答案1

得分: 1

请尝试以下代码。

    int[][] arrays = {{0, 1, 2, 3}, {4}, {5, 6}, {7},};
    int[][] sorted = Arrays.stream(arrays)
        .map(a -> new Object() {
            int sum = IntStream.of(a).sum();
            int[] array = a;
        })
        .sorted(Comparator.comparing(obj -> obj.sum))
        .map(obj -> obj.array)
        .toArray(int[][]::new);
    System.out.println(Arrays.deepToString(sorted));

输出结果:

[[4], [0, 1, 2, 3], [7], [5, 6]]
英文:

Try this.

int[][] arrays = {{0, 1, 2, 3}, {4}, {5, 6}, {7},};
int[][] sorted = Arrays.stream(arrays)
    .map(a -> new Object() {
        int sum = IntStream.of(a).sum();
        int[] array = a;
    })
    .sorted(Comparator.comparing(obj -> obj.sum))
    .map(obj -> obj.array)
    .toArray(int[][]::new);
System.out.println(Arrays.deepToString(sorted));

output

[[4], [0, 1, 2, 3], [7], [5, 6]]

huangapple
  • 本文由 发表于 2020年9月29日 05:14:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/64109730.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定