如何使用 Java 8 流迭代 x 次?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40573796/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to iterate x times using Java 8 stream?
提问by AlikElzin-kilaka
I have an old style for
loop to do some load tests:
我有一个旧式for
循环来做一些负载测试:
For (int i = 0 ; i < 1000 ; ++i) {
if (i+1 % 100 == 0) {
System.out.println("Test number "+i+" started.");
}
// The test itself...
}
How can I use new Java 8 stream API to be able to do this without the for
?
我怎样才能使用新的 Java 8 流 API 来做到这一点,而无需for
?
Also, the use of the stream would make it easy to switch to parallel stream. How to switch to parallel stream?
此外,使用流可以很容易地切换到并行流。如何切换到并行流?
* I'd like to keep the reference to i
.
* 我想保留对i
.
采纳答案by Andrew Tobilko
IntStream.range(0, 1000)
/* .parallel() */
.filter(i -> i+1 % 100 == 0)
.peek(i -> System.out.println("Test number " + i + " started."))
/* other operations on the stream including a terminal one */;
If the test is running on each iteration regardless of the condition (take the filter
out):
如果测试在每次迭代中运行而不管条件如何(filter
取出):
IntStream.range(0, 1000)
.peek(i -> {
if (i + 1 % 100 == 0) {
System.out.println("Test number " + i + " started.");
}
}).forEach(i -> {/* the test */});
Another approach (if you want to iterate over an index with a predefined step, as @Tunakimentioned) is:
另一种方法(如果您想使用预定义的步骤迭代索引,如@Tunaki所述)是:
IntStream.iterate(0, i -> i + 100)
.limit(1000 / 100)
.forEach(i -> { /* the test */ });
There is an awesome overloaded method Stream.iterate(seed, condition, unaryOperator)
in JDK 9 which perfectly fits your situation and is designed to make a stream finite and might replace a plain for
:
Stream.iterate(seed, condition, unaryOperator)
JDK 9 中有一个很棒的重载方法,它非常适合您的情况,旨在使流有限并可能替换普通的for
:
Stream<Integer> stream = Stream.iterate(0, i -> i < 1000, i -> i + 100);
回答by developer
You can use IntStream
as shown below and explained in the comments:
您可以使用IntStream
如下所示并在评论中解释:
(1) Iterate IntStream
range from 1 to 1000
(1) 迭代IntStream
范围从 1 到 1000
(2) Convert to parallel
stream
(2) 转换为parallel
流
(3) Apply Predicate
condition to allow integers with (i+1)%100 == 0
(3) 应用Predicate
条件以允许整数(i+1)%100 == 0
(4) Now convert the integer to a string "Test number "+i+" started."
(4) 现在将整数转换为字符串 "Test number "+i+" started."
(5) Output to console
(5) 输出到控制台
IntStream.range(1, 1000). //iterates 1 to 1000
parallel().//converts to parallel stream
filter( i -> ((i+1)%100 == 0)). //filters numbers & allows like 99, 199, etc..)
mapToObj((int i) -> "Test number "+i+" started.").//maps integer to String
forEach(System.out::println);//prints to the console