How to flatten a 2D array into a sorted one-dimensional array in Java

2 Answers

0 votes
import java.util.Arrays;

public class Flatten2DArrayIntoASorted1DArray_Java {
    public static void main(String[] args) {
        int[][] array2d = {
            {4, 5, 3},
            {30, 20},
            {10},
            {1, 2, 6, 7, 8},
        };

        int[] arr = Arrays.stream(array2d)
                          .flatMapToInt(Arrays::stream)
                          .sorted()
                          .toArray();

        System.out.println(Arrays.toString(arr).replaceAll("[\\[\\]]", ""));
    }
}


/*
run:

1, 2, 3, 4, 5, 6, 7, 8, 10, 20, 30

*/

 



answered Aug 15, 2024 by avibootz
edited Aug 15, 2024 by avibootz
0 votes
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

*/

 



answered 17 hours ago by avibootz

Related questions

...