如何使用Streams将2D数组转换为2D列表?

Ale*_*iam 5 java multidimensional-array java-stream

我试过这个 StackOverflow答案的代码,但是我得到了错误Cannot infer type argument(s) for <R> map(Function<? super T,? extends R>):

//data is int[][]
Arrays.stream(data)
    .map(i -> Arrays.stream(i)
        .collect(Collectors.toList()))
            .collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)

Sto*_*ica 6

Arrays.stream将经历每int[]一个int[][].您可以将其转换int[]IntStream.然后,为了将ints 流转换为a List<Integer>,首先需要将它们打包.一旦装箱到Integers,您可以将它们收集到列表中.最后将流收集List<Integer>到一个列表中.

List<List<Integer>> list = Arrays.stream(data)
    .map(row -> IntStream.of(row).boxed().collect(Collectors.toList()))
    .collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)

演示.