[英]printing 2D array using IntStream's flatMap method
我有一個我想用IntStream
打印的2D數組。
這是陣列,
int[][] twoD = { { 1, 2 }, { 3, 4 }, { 5, 6 } };
現在,使用嵌套循環,這可以像,
for (int i = 0; i < twoD.length; i++) {
for (int j = 0; j < twoD[i].length; j++) {
System.out.println(twoD[i][j]);
}
}
但我想使用IntStream
。 我最近了解了它可以用來實現它的flatMap
方法,所以我嘗試了這個,
IntStream.range(0, twoD.length)
.flatMap(j -> IntStream.range(0, twoD[j].length))
.forEach(System.out::print);
它輸出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);
但它在map(i -> twoD[i])
上給出錯誤map(i -> twoD[i])
,
Type mismatch: cannot convert from int[] to int
但如果它是1D陣列那么它會起作用,例如,
int[] oneD = { 1, 2, 3, 4, 5, 6 };
IntStream.range(0, oneD.length)
.map(i -> oneD[i])
.forEach(System.out::print);
如何使用上述方法打印2D陣列?
我認為你過於復雜。 你可以這樣做:
Stream.of(twoD).flatMapToInt(IntStream::of).forEach(System.out::println);
它的作用是:
int[][]
數組中獲取Stream<int[]>
flatMap
每個int[]
IntStream
到一個IntStream
以便返回一個IntStream
2D數組所有元素的IntStream
IntStream.range(0, twoD.length)
.mapToObj(i -> twoD[i])
.flatMapToInt(IntStream::of)
.forEach(System.out::print);
產生相同的輸出,但你可以看到它不是很可讀。 在這里,您不需要流式索引,因此使用flatMapToInt
的第一種方法是最好的。
既然你的解決方案無法編譯?
這是因為map
上的IntStream
預期的映射功能,讓你回一個int
,但你給一個int[]
您需要使用mapToObj
然后再使用flatMapToInt
來獲取IntStream
並最終打印內容(盡管這不是唯一的解決方案)。
IntStream.range(0, twoD.length) .mapToObj(i -> twoD[i]) .flatMapToInt(IntStream::of) .forEach(System.out::print);
你有可讀性嗎? 不是真的,所以我建議使用第一種清晰簡潔的方法。
請注意,最后一個解決方案也可以寫為:
IntStream.range(0, twoD.length) .flatMap(i -> IntStream.of(twoD[i])) .forEach(System.out::print);
......但我還是喜歡第一種方法! :)
為什么不流式傳輸數組:
Arrays.stream(twoD)
.flatMapToInt(Arrays::stream)
.forEach(System.out::println);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.