takeWhile() working differently with flatmap

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

    This is a bug no matter how I look at it - and thank you Holger for your comments. I did not want to put this answer in here (seriously!), but none of the answer clearly states that this is a bug.

    People are saying that this has to with ordered/un-ordered, and this is not true as this will report true 3 times:

    Stream s1 = Arrays.stream(strArray);
    System.out.println(s1.spliterator().hasCharacteristics(Spliterator.ORDERED));
    
    Stream s2 = Arrays.stream(strArray)
                .flatMap(indStream -> Arrays.stream(indStream));
    System.out.println(s2.spliterator().hasCharacteristics(Spliterator.ORDERED));
    
    Stream s3 = Arrays.stream(strArray)
                .flatMap(indStream -> Arrays.stream(indStream))
                .takeWhile(ele -> !ele.equalsIgnoreCase("Sample4"));
    System.out.println(s3.spliterator().hasCharacteristics(Spliterator.ORDERED));
    

    It's very interesting also that if you change it to:

    String[][] strArray = { 
             { "Sample1", "Sample2" }, 
             { "Sample3", "Sample5", "Sample4" }, // Sample4 is the last one here
             { "Sample7", "Sample8" } 
    };
    

    then Sample7 and Sample8 will not be part of the output, otherwise they will. It seems that flatmap ignores a cancel flag that would be introduced by dropWhile.

提交回复
热议问题