16

Maybe a normal for loop is still the right way but I wanted to see if there is a more succinct way to do it in java 8.

 for (int i = 0; i < LIMIT; i++) {
     // Code
 }

Is there a more java 8 way to do this. I don't actually need i just need to repeat something x number of times.

Thanks, Nathan

Nath5
  • 1,665
  • 5
  • 28
  • 46

2 Answers2

19

The best way I can see on how to do this would be something like IntStream.range(0, LIMIT).forEach($ -> code).

Voo
  • 29,040
  • 11
  • 82
  • 156
  • 1
    Could you clarify why you use dollar sign for the identifier? Is it a convention to use `$` when it's unused. Also, could this ever cause a conflict (for the same reason `$` usage in identifiers is cautioned) – swalog Sep 28 '15 at 13:12
  • 1
    @swalog In other languages `_` is used to signify unused parameters, but that isn't allowed in Java, so just pick what you want. I'm not the only one using it (see Peter's answer), but I doubt there's any wide spread idiom. The compiler uses `$` for inner classes (no risk there), a few special fields like `$assertionsDisabled ` and presumably (not checked) methods created from lambdas (again no risk there). Pick whatever you want. – Voo Sep 28 '15 at 13:59
  • You will to do a lot if the 'code' called in the Lambda function throws checked exception. You cannot throw a checked exception in Java8 Lambda. – Shubham Jun 20 '17 at 08:28
9

One of the reasons to use IntStream is to add parallel-ism, assuming you understand the impact of this.

IntStream.range(0, LIMIT).parallel().forEach($ -> {
    // some thing thread safe.
});
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130