import java.util.Arrays;
public class Flatten2DArrayIntoASorted1DArray_Java {
// Function that flattens a 2D int array and returns a sorted 1D array
public static int[] flattenAndSort(int[][] array2d) {
// Stream each row, flatten into one IntStream, sort, and convert to array
return Arrays.stream(array2d)
.flatMapToInt(Arrays::stream)
.sorted()
.toArray();
}
public static void main(String[] args) {
int[][] array2d = {
{4, 5, 3},
{30, 20},
{10},
{1, 2, 6, 7, 8},
};
int[] arr = flattenAndSort(array2d);
// Print result without brackets
System.out.println(Arrays.toString(arr).replaceAll("[\\[\\]]", ""));
}
}
/*
run:
1, 2, 3, 4, 5, 6, 7, 8, 10, 20, 30
*/