如何使用Java 8流迭代x次?

Ali*_*aka 9 java for-loop java-8 java-stream

我有一个旧的样式for循环来做一些负载测试:

For (int i = 0 ; i < 1000 ; ++i) {
  if (i+1 % 100 == 0) {
    System.out.println("Test number "+i+" started.");
  }
  // The test itself...
}
Run Code Online (Sandbox Code Playgroud)

如何在不使用新的Java 8流API的情况下执行此操作for

此外,使用流可以很容易地切换到并行流.如何切换到并行流?

*我想继续参考i.

And*_*lko 19

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 */;
Run Code Online (Sandbox Code Playgroud)

如果测试在每次迭代中运行而不考虑条件(filter取出):

IntStream.range(0, 1000)
         .peek(i -> {
             if (i + 1 % 100 == 0) {
                 System.out.println("Test number " + i + " started.");
             }
         }).forEach(i -> {/* the test */});
Run Code Online (Sandbox Code Playgroud)

另一种方法(如果您希望使用预定义步骤迭代索引,如@Tunaki所提到的)是:

IntStream.iterate(0, i -> i + 100)
         .limit(1000 / 100)
         .forEach(i -> { /* the test */ });
Run Code Online (Sandbox Code Playgroud)

Stream.iterate(seed, condition, unaryOperator)JDK 9中有一个非常棒的重载方法,它完全适合您的情况,旨在使流有限并可能取代普通for:

Stream<Integer> stream = Stream.iterate(0, i -> i < 1000, i -> i + 100);
Run Code Online (Sandbox Code Playgroud)