Reputation: 1
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.
Upvotes: 0
Views: 53
Reputation:
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]]
Upvotes: 1