展平嵌套数组

/**
 * 展平嵌套数组
 */
public static Stream<Object> java8Flatten(Object[] arr) {
    return Arrays.stream(arr).flatMap(obj -> obj instanceof Object[] ? java8Flatten((Object[]) obj) : Stream.of(obj));
}
Object[] arr = {1, 2, new Object[]{1, 2, 44}, 4};
Object[] arr1 = java8Flatten(arr).toArray();                                                // [1, 2, 1, 2, 44, 4]
Object[] arr2 = java8Flatten(arr).map(String::valueOf).toArray();                           // [1, 2, 1, 2, 44, 4]
String[] arr3 = java8Flatten(arr).map(String::valueOf).toArray(String[]::new);              // [1, 2, 1, 2, 44, 4]
List<String> arr4 = java8Flatten(arr).map(String::valueOf).collect(Collectors.toList());    // [1, 2, 1, 2, 44, 4]

你可能感兴趣的:(JAVA8,java)