AMRIT KUMAR
AMRIT KUMAR

Reputation: 1

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.

Upvotes: 0

Views: 53

Answers (1)

user4910279
user4910279

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

Related Questions