0

Is there a way to use streams to write this code:

    for (int i = 0; i < list.size(); i ++) {
        if (i % 1000 == 0) {
           doSomething();
        }
        doSomethingElse(list.get(i));
   }

Thanks!

Alexis C.
  • 91,686
  • 21
  • 171
  • 177
dardy
  • 433
  • 1
  • 6
  • 18

1 Answers1

3

You could use an IntStream for that... but why should you? It looks basically the same as what you wrote, but has some overhead due to the IntStream which is not really needed here.

IntStream.range(0, list.size())
         .forEach(i -> {
           if (i % 1000 == 0) {
             doSomething();
           }
           doSomethingElse(list.get(i));
         });

Without knowing what doSomething or doSomethingElse do, it's hard to make a better proposal. Maybe you want to (or should?) partition your list beforehand?

Roland
  • 22,259
  • 4
  • 57
  • 84
  • You're right. I thought that the code will be less verbose with streams but in this case, there is no need to use theme. Thanks! – dardy Feb 07 '17 at 14:44