英文:
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]]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论