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:

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");
}

Newsletter

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.

Email address:

Recent Jobs

No job listings found.

Join Us

With 1,240,600 monthly unique visitors and over 500 authors we are placed among the top Java related sites around. Constantly being on the lookout for partners; we encourage you to join us. So If you have a blog with unique and interesting content then you should check out our JCG partners program. You can also be a guest writer for Java Code Geeks and hone your writing skills!

Disclaimer

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. Examples Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.