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

AlikElzin-kilaka:

我有一个旧样式的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

安德鲁·托比尔科(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 */;

如果测试在每次迭代中都在运行,而不考虑条件(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 */ });

Stream.iterate(seed, condition, unaryOperator)JDK 9中有一个很棒的重载方法,它很适合您的情况,并且设计成使流有限,并可能替换纯文本for

Stream<Integer> stream = Stream.iterate(0, i -> i < 1000, i -> i + 100);

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章