7

What is the easiest and quickest way to execute a code block multiple times using a lambda expression in Java 8? For example, a code that will replace the following:

for (int i = 0; i < 20; i ++) {
 doSomething();
} 
0

1 Answer 1

7

You can use an IntStream.range, but I don't see much advantage to this approach over the loop you are already using.

IntStream.range(0,20).forEach(i -> doSomething());
Sign up to request clarification or add additional context in comments.

5 Comments

I was looking for something like that. Code is much cleaner this way. Thx.
One downside for it though is that it can't accept code which throws a checked exception. This is Java's fault since Consumer's Accept method can't throw a checked exception. baaah.
You could wrap the code which throws a checked exception in something which catches and rethrows as unchecked
or you could just use a for loop.
@pbabcdefp I completely agree with you. I really love Java 8's features and lambdas in particular, but IMHO there are things that are not made simpler by using lambdas. For loops are part of these things (especially when checked exceptions join the party).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.