Java?8’s 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[]? 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(flat));
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…