将循环转换为java 8流 [英] converting for loop to java 8 stream
问题描述
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中没有直接的等效。有两种可能:
-
使用
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);
-
使用
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:
Use
IntStream.iterate(y, x->x+2)
to define start value and increment. Then you have to modify the infinite stream bylimit
ing 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);
Use
IntStream.range(0, (11-y)/2)
to create an stream of the desired number of ascendingint
s and modify it with.map(t->y+t*2)
to have it produce the desired values of your innerfor
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屋!