Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate IntStream using java stream API

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?

like image 620
Dub Nazar Avatar asked Oct 25 '15 12:10

Dub Nazar


People also ask

How do I get an IntStream from an int?

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().

What is Java Util stream IntStream?

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.

What is the difference between stream and IntStream?

IntStream is a stream of primitive int values. Stream<Integer> is a stream of Integer objects.


2 Answers

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)
like image 155
Tunaki Avatar answered Oct 01 '22 14:10

Tunaki


Using my free StreamEx library two more solutions are possible in addition to ones proposed in @Tunaki answer.

  1. Using backport of takeWhile method which appears in JDK-9:

    IntStream is = IntStreamEx.iterate(3, i -> i + 2).takeWhile(i -> i*i <= n);
    
  2. Using three-argument IntStreamEx.rangeClosed which allows to specify the step:

    IntStream is = IntStreamEx.rangeClosed(3, (int) Math.sqrt(n), 2);
    
like image 27
Tagir Valeev Avatar answered Oct 01 '22 12:10

Tagir Valeev