将循环转换为java 8流 [英] converting for loop to java 8 stream

查看:152
本文介绍了将循环转换为java 8流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  for(

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

请帮忙!

解决方案

转换嵌套循环的规范方式是在流上使用 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) $ 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),让它为循环产生期望的内部值。



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

      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);
    

这篇关于将循环转换为java 8流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆