takeWhile() working differently with flatmap

前端 未结 4 470
被撕碎了的回忆
被撕碎了的回忆 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 13:10

    The reason for that is the flatMap operation also being an intermediate operations with which (one of) the stateful short-circuiting intermediate operation takeWhile is used.

    The behavior of flatMap as pointed by Holger in this answer is certainly a reference one shouldn't miss out to understand the unexpected output for such short-circuiting operations.

    Your expected result can be achieved by splitting these two intermediate operations by introducing a terminal operation to deterministically use an ordered stream further and performing them for a sample as :

    List sampleList = Arrays.stream(strArray).flatMap(Arrays::stream).collect(Collectors.toList());
    sampleList.stream().takeWhile(ele -> !ele.equalsIgnoreCase("Sample4"))
                .forEach(System.out::println);
    

    Also, there seems to be a related Bug#JDK-8075939 to trace this behavior already registered.

    Edit: This can be tracked further at JDK-8193856 accepted as a bug.

提交回复
热议问题