且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将循环转换为java 8流

更新时间:2022-10-20 19:25:54

转换嵌套循环的规范方式是在流上使用 flatMap ,例如

  IntStream.range(0,5).flatMap(i-> IntStream.range(i,10))
.forEach (的System.out ::的println);

您任务中棘手的部分是增加2,因为它在流API中没有直接的等效。有两种可能:


  1. 使用 IntStream.iterate(y,x-> x + 2 )来定义起始值和增量。然后你必须通过 limit 来修改无限流: .limit((11-y)/ 2)$ c
    $ b

    因此,您的循环的结果代码如下所示:

      IntStream.range(0,5)
    .flatMap(y-> IntStream.iterate(y,x-> x + 2).limit((11-y)/ 2)
    .map(x - > x + y))。forEach(System.out :: println);


  2. 使用 IntStream.range(0,(11-y) / 2)创建一个所需数量的升序流 int s并用 .map(t- > y + t * 2),让它为$ c>循环产生期望的内部值。



    然后,循环的结果代码如下所示:

      IntStream.range(0,5) 
    .flatMap(y-> IntStream.range(0,(11-y)/ 2).map(t-> y + t * 2).map(x - > x + y))
    .forEach(System.out :: println);



I was playing around with Java 8. I had some trouble converting this for loop into Java 8 Stream.

for (int y = 0; y < 5; y ++) {
    for (int x = y; x < 10; x += 2) {
        System.out.println(x+y);
    }
}

Please help!

The canonical way of converting nested loops is to use flatMap on a stream, e.g.

IntStream.range(0, 5).flatMap(i->IntStream.range(i, 10))
  .forEach(System.out::println);

The tricky part on your task is the increment by two as this has no direct equivalent in the stream API. There are two possibilities:

  1. Use IntStream.iterate(y, x->x+2) to define start value and increment. Then you have to modify the infinite stream by limiting the number of elements: .limit((11-y)/2).

    So the resulting code for your loop would look like:

    IntStream.range(0, 5)
        .flatMap(y->IntStream.iterate(y, x->x+2).limit((11-y)/2)
        .map(x -> x+y)).forEach(System.out::println);
    

  2. Use IntStream.range(0, (11-y)/2) to create an stream of the desired number of ascending ints and modify it with .map(t->y+t*2) to have it produce the desired values of your inner for loop.

    Then, the resulting code for your loop would look like:

    IntStream.range(0, 5)
        .flatMap(y->IntStream.range(0, (11-y)/2).map(t->y+t*2).map(x -> x+y))
        .forEach(System.out::println);