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!

1
  • 2
    Did you mean doSomethingElse(list.get(i)); ? Commented Feb 7, 2017 at 14:31

1 Answer 1

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?

Sign up to request clarification or add additional context in comments.

1 Comment

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!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.