【问题标题】:How can I convert a 2D array to a 2D list with Streams?如何使用 Streams 将 2D 数组转换为 2D 列表?
【发布时间】:2017-06-04 19:23:28
【问题描述】:

我已经尝试了this 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());

【问题讨论】:

    标签: java multidimensional-array java-stream


    【解决方案1】:

    试试StreamEx

    StreamEx.of(data).map(a -> IntStreamEx.of(a).boxed().toList()).toList();
    

    或者AbacusUtil,简单高效:

    Stream.of(data).map(a -> IntList.of(a).boxed()).toList();
    
    // Or:
    Seq.of(data).map(a -> IntList.of(a).boxed());
    

    它们都是空安全的。如果data 为空,则返回一个空列表

    【讨论】:

      【解决方案2】:

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

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

      Demo.

      【讨论】:

      • 没有理由将代码更改为IntStream.of; Arrays.stream 工作正常。 OP 代码中缺少的只是对boxed() 的调用……
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-26
      • 2019-06-11
      • 2022-08-03
      • 2014-08-31
      • 2019-02-07
      相关资源
      最近更新 更多