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
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));