Java 8 将代码块重复 x 次的方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30783552/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 17:39:39  来源:igfitidea点击:

Java 8 way to repeat a block of code x times

javajava-8

提问by Nath5

Maybe a normal for loop is still the right way but I wanted to see if there is a more succinct way to do it in java 8.

也许普通的 for 循环仍然是正确的方法,但我想看看在 java 8 中是否有更简洁的方法来做到这一点。

 for (int i = 0; i < LIMIT; i++) {
     // Code
 }

Is there a more java 8 way to do this. I don't actually need i just need to repeat something x number of times.

有没有更多的 java 8 方法来做到这一点。我实际上并不需要我只需要重复某件事 x 次。

Thanks, Nathan

谢谢,内森

回答by Voo

The best way I can see on how to do this would be something like IntStream.range(0, LIMIT).forEach($ -> code).

我能看到的关于如何做到这一点的最佳方式是类似于IntStream.range(0, LIMIT).forEach($ -> code).

回答by Peter Lawrey

One of the reasons to use IntStream is to add parallel-ism, assuming you understand the impact of this.

使用 IntStream 的原因之一是添加并行性,假设您了解其影响。

IntStream.range(0, LIMIT).parallel().forEach($ -> {
    // some thing thread safe.
});