Flatten nested arrays in java

The Stream API offers a compact and flexible solution. Using the method

private static Stream<Object> flatten(Object[] array) {
    return Arrays.stream(array)
        .flatMap(o -> o instanceof Object[] a? flatten(a): Stream.of(o));
}

or prior to JDK 16

private static Stream<Object> flatten(Object[] array) {
    return Arrays.stream(array)
        .flatMap(o -> o instanceof Object[]? flatten((Object[])o): Stream.of(o));
}

you can perform the operation as

Object[] array = { 1, 2, new Object[]{ 3, 4, new Object[]{ 5 }, 6, 7 }, 8, 9, 10 };
System.out.println("original: "+Arrays.deepToString(array));

Object[] flat = flatten(array).toArray();
System.out.println("flat:     "+Arrays.toString(flat));

or when you assume the leaf objects to be of a specific type:

int[] flatInt = flatten(array).mapToInt(Integer.class::cast).toArray();
System.out.println("flat int: "+Arrays.toString(flatInt));

Leave a Comment