本文介绍了IntStream按步骤迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何用IntStream在步骤(3)中遍历一系列数字(0-100)?
我试过 iterate
,但这永远不会停止执行。
IntStream.iterate(0,n - > n + 3).filter(x - > x> 0& amp; amp; ;& x< 100).forEach(System.out :: println)
解决方案实际上
范围
对此非常理想。 IntStream.range(0,100).filter(x - > x%3 == 0); // 107,566 ns / op [Average]
编辑:Holgers的解决方案是表现最快的解决方案。
由于以下代码行
<$ c(c)> IntStream.range(0,100).filter(x - > x%3 == 0).forEach((x) - > x = x + 2) $(b)b
IntStream.range(0,100/3).map(x - > x * 3).forEach((x) - > x = x + 2)
int limit =(100/3)+1;
IntStream.iterate(0,n - > n + 3).limit(limit).forEach((x) - > x = x + 2)
显示这些基准结果
基准模式Cnt得分错误单位
Benchmark.intStreamTest avgt 5 485,473±58,402 ns / op
Benchmark.intStreamTest2 avgt 5 202,135±7,237 ns / op
Benchmark.intStreamTest3 avgt 5 280,307±41,772 ns / op
How do you iterate through a range of numbers (0-100) in steps(3) with IntStream?
I tried iterate
, but this never stops executing.
IntStream.iterate(0, n -> n + 3).filter(x -> x > 0 && x < 100).forEach(System.out::println)
解决方案
Actually range
is ideal for this.
IntStream.range(0, 100).filter(x -> x % 3 == 0); //107,566 ns/op [Average]
Edit: Holgers's solution is the fastest performing solution.
Since the following lines of code
IntStream.range(0, 100).filter(x -> x % 3 == 0).forEach((x) -> x = x + 2);
IntStream.range(0, 100 / 3).map(x -> x * 3).forEach((x) -> x = x + 2);
int limit = ( 100 / 3 ) + 1;
IntStream.iterate(0, n -> n + 3).limit(limit).forEach((x) -> x = x + 2);
show these benchmark results
Benchmark Mode Cnt Score Error Units
Benchmark.intStreamTest avgt 5 485,473 ± 58,402 ns/op
Benchmark.intStreamTest2 avgt 5 202,135 ± 7,237 ns/op
Benchmark.intStreamTest3 avgt 5 280,307 ± 41,772 ns/op
这篇关于IntStream按步骤迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-22 10:35