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

前端 未结 7 1253
误落风尘
误落风尘 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:46

    I agree with other people this is a bug opened at JDK-8075939. And since it's still not fixed more than one year later. I would like to recommend you: AbacusUtil

    N.println("Result: " + Stream.of(1, 2, 3).peek(N::println).first().get());
    
    N.println("-----------");
    
    N.println("Result: " + Stream.of(1, 2, 3)
                            .flatMap(i -> Stream.of(i - 1, i, i + 1))
                            .flatMap(i -> Stream.of(i - 1, i, i + 1))
                            .peek(N::println).first().get());
    
    // output:
    // 1
    // Result: 1
    // -----------
    // -1
    // Result: -1
    

    Disclosure: I'm the developer of AbacusUtil.

提交回复
热议问题