【问题标题】:How to convert nested array to nested list using lambda?如何使用 lambda 将嵌套数组转换为嵌套列表?
【发布时间】:2020-07-14 13:50:28
【问题描述】:

更新: 使用Integer[][]作为src数组类型可以使下面的代码工作。


我想将int[][] 转换为List<List<Integer>> 并尝试使用:

int[][] arr = new int[][]{{2}, {3, 4}, {6, 5, 7}, {4, 1, 8, 3}};
List<List<Integer>> ll = Arrays.stream(arr)
        .map(Arrays::asList) //  I expect this produces Stream<List<Integer>> but it was actually a Stream<List<int[]>>.
        .collect(Collectors.toList());

编译器发出错误:

|  Error:
|  incompatible types: inference variable T has incompatible bounds
|      equality constraints: java.util.List<java.lang.Integer>
|      lower bounds: java.util.List<int[]>
|          List<List<Integer>> ll = Arrays.stream(arr).map(Arrays::asList).collect(Collectors.toList());
|                                   ^-----------------------------------------------------------------^

【问题讨论】:

  • @Naman 我看不出这个问题与任何链接问题的重复。
  • @hev1 你通过this answer了吗?

标签: java arrays java-8


【解决方案1】:

Arrays.asList 不适用于原语(至少,不是您想要的方式:Arrays.asList(new int[n]) 是带有一个元素的 List&lt;int[]&gt;,而不是带有 n 元素的 List&lt;Integer&gt;)。

相反,映射到IntStream(给你一个IntStream),将元素装箱(给你一个Stream&lt;Integer&gt;),然后收集到一个列表(给你一个List&lt;Integer&gt;:

List<List<Integer>> ll = Arrays.stream(arr)
    .map(a -> IntStream.of(a).boxed().collect(toList()))
    .collect(toList());

请注意,如果您使用 Guava,则可以使用 Ints.asList:

List<List<Integer>> ll = Arrays.stream(arr)
    .map(Ints::asList)
    .collect(toList());

其他库也可能有int[] -&gt; List&lt;Integer&gt; 方法;这只是我知道存在的一个。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-02
    • 2012-06-03
    • 1970-01-01
    • 2020-01-24
    • 2020-09-03
    • 1970-01-01
    • 2010-11-15
    • 1970-01-01
    相关资源
    最近更新 更多