使用 IntStream 的 flatMap 方法打印二维数组

Joe*_*Joe 4 java java-8

我有一个二维数组,我想使用IntStream.

这是数组,

int[][] twoD = { { 1, 2 }, { 3, 4 }, { 5, 6 } };
Run Code Online (Sandbox Code Playgroud)

现在,使用嵌套循环可以这样做,

    for (int i = 0; i < twoD.length; i++) {
        for (int j = 0; j < twoD[i].length; j++) {
            System.out.println(twoD[i][j]);
        }
    }
Run Code Online (Sandbox Code Playgroud)

但我想使用IntStream. 我最近了解了flatMap我可以用来实现它的方法,所以我尝试了这个,

    IntStream.range(0, twoD.length)
            .flatMap(j -> IntStream.range(0, twoD[j].length))
            .forEach(System.out::print);
Run Code Online (Sandbox Code Playgroud)

它输出010101.

在输出中的一个原因010101是,010101在指数值不是数组中的值,我必须使用类似这些值到数组值映射,i -> twoD[i]

所以我尝试了这个,

    IntStream.range(0, twoD.length)
            .map(i -> twoD[i])
            .flatMap(j -> IntStream.range(0, twoD[j].length))
            .forEach(System.out::print);
Run Code Online (Sandbox Code Playgroud)

但它给出了错误map(i -> twoD[i])

Type mismatch: cannot convert from int[] to int
Run Code Online (Sandbox Code Playgroud)

但如果它是一维数组,那么它就会起作用,例如,

int[] oneD = { 1, 2, 3, 4, 5, 6 };

IntStream.range(0, oneD.length)
.map(i -> oneD[i])
.forEach(System.out::print);
Run Code Online (Sandbox Code Playgroud)

如何使用上述方法打印二维数组?

Ale*_* C. 7

我认为你把事情复杂化了。你可以这样做:

Stream.of(twoD).flatMapToInt(IntStream::of).forEach(System.out::println);
Run Code Online (Sandbox Code Playgroud)

它的作用是:

  • Stream<int[]>int[][]数组中获取一个
  • flatMap每个int[]到 anIntStream以便您返回IntStream带有 2D 数组的所有元素的an
  • 对于每个元素,打印它


你想要做的是可以实现但不是很可读。嵌套循环的正式翻译是:

IntStream.range(0, twoD.length)
         .forEach(i -> IntStream.range(0, twoD[i].length)
                                .forEach(j -> System.out.println(twoD[i][j])));
Run Code Online (Sandbox Code Playgroud)

它产生相同的输出,但正如您所见,它的可读性不是很强。在这里,您不需要流式传输索引,因此第一种方法flatMapToInt是最好的。

现在为什么您的解决方案无法编译?

这是因为map在一个IntStream预期的映射功能,让你回一个int,但你给的int[]。您需要使用mapToObj然后再次flatMapToInt获取IntStream并最终打印内容(但这不是唯一的解决方案)。

IntStream.range(0, twoD.length)
         .mapToObj(i -> twoD[i])
         .flatMapToInt(IntStream::of)
         .forEach(System.out::print);
Run Code Online (Sandbox Code Playgroud)

你是否提高了可读性?不是真的,所以我建议使用第一种清晰简洁的方法。

请注意,最后一个解决方案也可以写成:

IntStream.range(0, twoD.length)
         .flatMap(i -> IntStream.of(twoD[i]))
         .forEach(System.out::print);
Run Code Online (Sandbox Code Playgroud)

...但我还是更喜欢第一种方法!:)

  • @Joe 我没有得到这个要求。`IntStream` 是一个 `Stream`。所以首先使用 `Stream.of` 来获取 `Stream&lt;int[]&gt;`,然后使用 `IntStream` 来打印元素。我仍然更新了我的答案来解释为什么你会遇到编译错误,尽管第一个解决方案是 IMO 最好和最干净的。 (3认同)