Why filter() after flatMap() is “not completely” lazy in Java streams?

前端 未结 7 1156
误落风尘
误落风尘 2020-11-22 08:17

I have the following sample code:

System.out.println(
       \"Result: \" +
        Stream.of(1, 2, 3)
                .filter(i -> {
                             


        
7条回答
  •  隐瞒了意图╮
    2020-11-22 08:50

    In my free StreamEx library I introduced the short-circuiting collectors. When collecting sequential stream with short-circuiting collector (like MoreCollectors.first()) exactly one element is consumed from the source. Internally it's implemented in quite dirty way: using a custom exception to break the control flow. Using my library your sample could be rewritten in this way:

    System.out.println(
            "Result: " +
                    StreamEx.of(1, 2, 3)
                    .flatMap(i -> Stream.of(i - 1, i, i + 1))
                    .flatMap(i -> Stream.of(i - 1, i, i + 1))
                    .filter(i -> {
                        System.out.println(i);
                        return true;
                    })
                    .collect(MoreCollectors.first())
                    .get()
            );
    

    The result is the following:

    -1
    Result: -1
    

提交回复
热议问题