How to create an IntStream using the Java thread API

How can I replace this code with the new Java Stream API:

int n = someFunction(); // n > 0 for (int i = 3; i * i <= n; i += 2) System.out.print(i); 

I tried using IntStream.iterate(3, i -> i + 2) , but I cannot add a stop condition.

As I understand it, I can not use the .limit(int) method here.

Any ideas?

+5
source share
2 answers

You can use limit(int) : you will need to determine how many elements will be between 3 and sqrt(n) in step 2. There is exactly (sqrt(n) - 3) / 2 + 1 , so you can write:

 IntStream.iterate(3, i -> i + 2).limit((int) (Math.sqrt(n) - 3) / 2 + 1); 

Having said that, you can also create a closed range from 3 to sqrt(n) and filter out even values, for example:

 IntStream.rangeClosed(3, (int) Math.sqrt(n)).filter(i -> i % 2 > 0) 
+5
source

Using my free StreamEx library, in addition to the ones suggested by @Tunaki's answer, two more solutions are possible.

  • Using the backport of the takeWhile method, which appears in JDK-9:

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

     IntStream is = IntStreamEx.rangeClosed(3, (int) Math.sqrt(n), 2); 
+2
source

Source: https://habr.com/ru/post/1234469/


All Articles