JavaRush /Java Blog /Random EN /Creating Your Own Loop Using Lambda Expressions in Java 8...
gnev
Level 24

Creating Your Own Loop Using Lambda Expressions in Java 8

Published in the Random EN group
There is no simple construct in Java for repeating something N number of times. Of course, we can create a for loop, but in the vast majority of cases we don't really care what kind of variable we create in the loop. We just want some part of the code to be repeated N times and that's it. With the introduction of lambda expressions in Java 8, you can use something like this: public class RepeatDemo { public static void main(String[] args) { // Повтор одной строки repeat(10, () -> System.out.println("HELLO")); // Повтор нескольких строк repeat(10, () -> { System.out.println("HELLO"); System.out.println("WORLD"); }); } static void repeat(int n, Runnable r) { for (int i = 0; i < n; i++) r.run(); } } It's probably not as pleasing to the eye or as obvious as a good old for loop, but it does get rid of an extra variable in the loop. If only Java 8 would take it a step further and provide "chocolate" syntax for the arguments in lambda expressions, then we would have something like Scala/Groovy code, which would make the code much more visual. For example: // Ну разве не здорово было бы иметь такую конструкцию в Java? repeat(10) { System.out.println("HELLO"); System.out.println("WORLD"); } Source
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION