簡體   English   中英

使用IntStream的flatMap方法打印2D數組

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM