How I can replace this code with new Java Stream API:
int n = someFunction(); // n > 0
for (int i = 3; i * i <= n; i += 2)
System.out.print(i);
I have tried to using IntStream.iterate(3, i -> i + 2)
, but I can't add stop condition.
As I understand I can't use .limit(int)
method here.
Any ideas?
Since you created a Stream with a single element, you can use findFirst() to get that element: int randInt = new Random(). ints(1,60,121). findFirst().
Java IntStream class is a specialization of Stream interface for int primitive. It represents a stream of primitive int-valued elements supporting sequential and parallel aggregate operations. IntStream is part of the java. util. stream package and implements AutoCloseable and BaseStream interfaces.
IntStream is a stream of primitive int values. Stream<Integer> is a stream of Integer objects.
You could use limit(int)
: you would have to determine how many elements are going to be between 3 and sqrt(n)
by steps of 2. There are exactly (sqrt(n) - 3) / 2 + 1
elements, so you could write:
IntStream.iterate(3, i -> i + 2).limit((int) (Math.sqrt(n) - 3) / 2 + 1);
Having said that, you could also create a closed range from 3 to sqrt(n)
and filter out the even values, like this:
IntStream.rangeClosed(3, (int) Math.sqrt(n)).filter(i -> i % 2 > 0)
Using my free StreamEx library two more solutions are possible in addition to ones proposed in @Tunaki answer.
Using backport of takeWhile
method which appears in JDK-9:
IntStream is = IntStreamEx.iterate(3, i -> i + 2).takeWhile(i -> i*i <= n);
Using three-argument IntStreamEx.rangeClosed
which allows to specify the step:
IntStream is = IntStreamEx.rangeClosed(3, (int) Math.sqrt(n), 2);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With