Home » Java » Core Java » Creating your own loop structure in Java 8 lambda

About Zemian Deng

Creating your own loop structure in Java 8 lambda

Java doesn’t have an easy construct of repeat something N number of times. We can make a for loop of course, but many times we don’t even care about the variable that we created in the loop. We just want repeat N times of some code and that’s it. With the lambda available in Java 8, you may attempt something like this:

 
 
 
 
 
 

public class RepeatDemo {
    public static void main(String[] args) {
        // One liner repeat
        repeat(10, () -> System.out.println("HELLO"));

        // Multi-liners repeat
        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();
    }
}

Probably not as eye pleasing or straight forward as the good fashion for-loop, but you do get rid of the unnecessary loop variable. Only if Java 8 would go extra mile and treat the lambda argument in method with sugar syntax, then we could have it something like the Scala/Groovy style, which makes code more smoother. For example:

 // Wouldn't this be nice to have in Java?
        repeat(10) {
            System.out.println("HELLO");
            System.out.println("WORLD");
        }

Hum….

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

and many more ....

2 comments

  1. interesting post, thanks…
    I created a simple class with Builder pattern that creates a loop with this usage style :

    link

    public static void main(String[] args) {
    loop().from(2).to(10).doIt(() -> System.out.println(“Hello World!”));
    }

  2. Hi, unless you do want to get rid of redundant loop variable why not to do it this way:

    import static java.util.stream.IntStream.*;

    range(1, 5).forEach((i)-> System.out.println(“HELLO”));

Leave a Reply

Your email address will not be published. Required fields are marked *

*


× one = 4

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Do you want to know how to develop your skillset and become a ...

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!
Get ready to Rock!
To download the books, please verify your email address by following the instructions found on the email we just sent you.

THANK YOU!

Close