代码之家  ›  专栏  ›  技术社区  ›  Amit Saha

Java Stream iterate在检查奇偶时不使用谓词

  •  -1
  • Amit Saha  · 技术社区  · 2 年前

            Stream<Integer> stream = Stream.iterate(0, s-> ((s<10) && (s%2==0)),  s-> s+1);
            stream.forEach(System.out::println);
    

    问题是它只是打印0。

            Stream<Integer> stream = Stream.iterate(0, s-> (s<10),  s-> s+1);
            stream.forEach(System.out::println);
    

    如果我删除s<10,只需保持s%2==0,并设置一个限制。我仍然只得到0作为输出。

            Stream<Integer> stream = Stream.iterate(0, s-> (s%2==0),  s-> s+1);
            stream.limit(10).forEach(System.out::println);
    

    我无法理解我错在哪里。我知道我可以用filter实现这一点,但关键是我无法识别我的错误,而使用Lambda我无法在eclipse中调试。

    2 回复  |  直到 2 年前
        1
  •  0
  •   Jens    2 年前

    使用:

      IntStream.range(0,10).filter(s-> s%2==0).forEach(System.out::println);
    

    0
    2
    4
    6
    8
    
        2
  •  0
  •   TheSmith1222    2 年前

    代码:

    Stream<Integer> stream = Stream.iterate( 0, s -> s < 10, s -> s + 1 )
            .filter( s -> ( s % 2 ) == 0 );
    
    stream.forEach( System.out::println );
    

    输出:

    0
    2
    4
    6
    8