Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
368 views
in Technique[技术] by (71.8m points)

java - IntStream iterate in steps

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)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...