Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 way to repeat a block of code x times [duplicate]

Tags:

java

java-8

Maybe a normal for loop is still the right way but I wanted to see if there is a more succinct way to do it in java 8.

 for (int i = 0; i < LIMIT; i++) {
     // Code
 }

Is there a more java 8 way to do this. I don't actually need i just need to repeat something x number of times.

Thanks, Nathan

like image 339
Nath5 Avatar asked Jun 11 '15 14:06

Nath5


People also ask

How do you repeat a block of code in Java?

The while loop in Java is a so-called condition loop. This means repeating a code sequence, over and over again, until a condition is met. In other words, you use the while loop when you want to repeat an operation as long as a condition is met.

How do you write a for loop in Java 8?

Java 8 has introduced a new way to loop over a List or Collection, by using the forEach() method of the new Stream class. You can iterate over any Collection like List, Set, or Map by converting them into a java. util. sttream.

How do you repeat a line in Java?

What you want to do is use a nested for loop (i.e. a loop inside a loop). The outer loop will print line by line by first printing the string, then starting new line. A new line is added by System. out.

Which loop should I use when I know how many times a task needs to be repeated?

Enumerated loops are loops that are used when you know in advance how many times you want to loop. In Java, these are called for loops.


1 Answers

The best way I can see on how to do this would be something like IntStream.range(0, LIMIT).forEach($ -> code).

like image 183
Voo Avatar answered Oct 04 '22 20:10

Voo