for loop - How to iterate x times using Java 8 stream? -


this question has answer here:

i have old style for loop load tests:

for (int = 0 ; < 1000 ; ++i) {   if (i+1 % 100 == 0) {     system.out.println("test number "+i+" started.");   }   // test itself... } 

how can use new java 8 stream api able without for?

also, use of stream make easy switch parallel stream. how switch parallel stream?

* i'd keep reference i.

intstream.range(0, 1000)          /* .parallel() */          .filter(i -> i+1 % 100 == 0)          .peek(i -> system.out.println("test number " + + " started."))          /* other operations on stream including terminal 1 */; 

if test running on each iteration regardless of condition (take filter out):

intstream.range(0, 1000)          .peek(i -> {              if (i + 1 % 100 == 0) {                  system.out.println("test number " + + " started.");              }          }).foreach(i -> {/* test */}); 

another approach (if want iterate on index predefined step, @tunaki mentioned) is:

intstream.iterate(0, -> + 100)          .limit(1000 / 100)          .foreach(i -> { /* test */ }); 

there awesome overloaded stream.iterate(seed, condition, unaryoperator) in jdk 9 fits situation , designed make stream finite , replace old-fashioned fors:

stream<integer> stream = stream.iterate(0, -> < 1000, -> + 100); 

Comments

Popular posts from this blog

php - How to display all orders for a single product showing the most recent first? Woocommerce -

asp.net - How to correctly use QUERY_STRING in ISAPI rewrite? -

angularjs - How restrict admin panel using in backend laravel and admin panel on angular? -