我有一个旧式的for
循环来进行一些负载测试:
For (int i = 0 ; i < 1000 ; ++i) {
if (i+1 % 100 == 0) {
System.out.println("Test number "+i+" started.");
}
// The test itself...
}
如何使用新的Java 8流API完成这个功能而不需要使用for
循环?
此外,使用流也可以轻松切换到并行流。如何切换到并行流?
* 我想保留对i
的引用。
我有一个旧式的for
循环来进行一些负载测试:
For (int i = 0 ; i < 1000 ; ++i) {
if (i+1 % 100 == 0) {
System.out.println("Test number "+i+" started.");
}
// The test itself...
}
如何使用新的Java 8流API完成这个功能而不需要使用for
循环?
此外,使用流也可以轻松切换到并行流。如何切换到并行流?
* 我想保留对i
的引用。
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 */;
如果测试在每次迭代中都运行,而不考虑条件(去掉filter
):
IntStream.range(0, 1000)
.peek(i -> {
if (i + 1 % 100 == 0) {
System.out.println("Test number " + i + " started.");
}
}).forEach(i -> {/* the test */});
另一种方法(如果你想要按照预定义的步长迭代索引,就像@Tunaki提到的那样)是:
IntStream.iterate(0, i -> i + 100)
.limit(1000 / 100)
.forEach(i -> { /* the test */ });
在JDK 9中有一个非常棒的方法Stream.iterate(seed, condition, unaryOperator)
,它完美地适合您的情况,并旨在使流变为有限流,可能会取代简单的for
循环:
Stream<Integer> stream = Stream.iterate(0, i -> i < 1000, i -> i + 100);
IntStream
,并在注释中进行解释:IntStream
范围从1到1000parallel
流Predicate
条件以允许具有(i+1)%100 == 0
的整数"Test number "+i+" started."
(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
i
是一个原始类型,那么短语“我想保留对i的引用”是什么意思? - Andrew TobilkoIntStream.range(0, 1000).filter(i->((i+1)%100 ==0)).forEach(i->System.out.printf("Test number %d started.%n", i));
- Naruto Biju Modei
值运行,而不是每100个一次。这是你的意图吗?你是否想要迭代一个具有预定义步长的索引,就像这里所示:http://stackoverflow.com/questions/32586604/is-it-possible-to-use-streams-intrange-function? - Tunaki