我有一个二维数组,我想使用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)
如何使用上述方法打印二维数组?
我认为你把事情复杂化了。你可以这样做:
Stream.of(twoD).flatMapToInt(IntStream::of).forEach(System.out::println);
Run Code Online (Sandbox Code Playgroud)
它的作用是:
Stream<int[]>从int[][]数组中获取一个flatMap每个int[]到 anIntStream以便您返回IntStream带有 2D 数组的所有元素的anIntStream.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)
...但我还是更喜欢第一种方法!:)
| 归档时间: |
|
| 查看次数: |
2296 次 |
| 最近记录: |