takeWhile() working differently with flatmap

前端 未结 4 431
被撕碎了的回忆
被撕碎了的回忆 2021-01-30 12:18

I am creating snippets with takeWhile to explore its possibilities. When used in conjunction with flatMap, the behaviour is not in line with the expectation. Please find the cod

4条回答
  •  粉色の甜心
    2021-01-30 12:53

    If you look at the documentation for takeWhile:

    if this stream is ordered, [returns] a stream consisting of the longest prefix of elements taken from this stream that match the given predicate.

    if this stream is unordered, [returns] a stream consisting of a subset of elements taken from this stream that match the given predicate.

    Your stream is coincidentally ordered, but takeWhile doesn't know that it is. As such, it is returning 2nd condition - the subset. Your takeWhile is just acting like a filter.

    If you add a call to sorted before takeWhile, you'll see the result you expect:

    Arrays.stream(strArray)
          .flatMap(indStream -> Arrays.stream(indStream))
          .sorted()
          .takeWhile(ele -> !ele.equalsIgnoreCase("Sample4"))
          .forEach(ele -> System.out.println(ele));
    

提交回复
热议问题