Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 815
JasperJ Avatar asked Nov 01 '16 11:11

JasperJ


People also ask

What is the difference between Stream and IntStream?

What is the difference between both? IntStream is a stream of primitive int values. Stream<Integer> is a stream of Integer objects.

What is IntStream of in Java?

Return Value : IntStream of(int… values) returns a sequential ordered stream whose elements are the specified values. Example 1 : Java.

How do I filter IntStream?

IntStream filter() method in JavaThe filter() method of the IntStream class in Java returns a stream consisting of the elements of this stream that match the given predicate. Here, the predicate parameter is a stateless predicate to apply to each element to determine if it should be included.

What is IntStream parallel?

The parallel() method of the IntStream class in Java returns an equivalent parallel stream. The method may return itself, either because the stream was already parallel, or because the underlying stream state was modified to be parallel. The syntax is as follows: IntStream parallel()


2 Answers

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
like image 91
JasperJ Avatar answered Sep 29 '22 11:09

JasperJ


Actually you can also achieve the same results with a combination of peek and allMatch:

IntStream.iterate(0, n -> n + 3).peek(n -> System.out.printf("%d,", n)).allMatch(n -> n < 100 - 3);

This prints

0,3,6,9,12,15,18,21,24,27,30,33,36,39,42,45,48,51,54,57,60,63,66,69,72,75,78,81,84,87,90,93,96,99,

But nevertheless, this one is faster:

IntStream.range(0, 100 / 3 + 1).map(x -> x * 3).forEach((x) -> System.out.printf("%d,", x));

Java 9 Update:

Now the same iteration easier to achieve with Java 9:

Stream.iterate(0, i -> i <= 100, i -> 3 + i).forEach(i -> System.out.printf("%d,", i));
like image 22
gil.fernandes Avatar answered Sep 29 '22 12:09

gil.fernandes