且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在java中展平嵌套数组

更新时间:2022-11-21 18:52:50

Java 8 的 Stream API 提供了一个紧凑而灵活的解决方案.使用方法

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));