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….

Related Whitepaper:

Functional Programming in Java: Harnessing the Power of Java 8 Lambda Expressions

Get ready to program in a whole new way!

Functional Programming in Java will help you quickly get on top of the new, essential Java 8 language features and the functional style that will change and improve your code. This short, targeted book will help you make the paradigm shift from the old imperative way to a less error-prone, more elegant, and concise coding style that’s also a breeze to parallelize. You'll explore the syntax and semantics of lambda expressions, method and constructor references, and functional interfaces. You'll design and write applications better using the new standards in Java 8 and the JDK.

Get it Now!  

2 Responses to "Creating your own loop structure in Java 8 lambda"

  1. Hamid says:

    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. ken says:

    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


4 − = three



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books