Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Skip items while iterating over a long list, whats more efficient?

Tags:

java

iteration

I am working with a java.util.List which is expected to contain approximately 70k Objects. It is built up from an ordered database query, so it is always in the same order every time. This list is being iterated over as part of a long running task which can get halted due to external issues. So I need to skip X elements in the list the next time the task runs.

Handling this in the database query that builds the list is not an option for various reasons.

What is the most efficient way to skip over X items in a list before doing the heavy lifting?

int skip = getNumberOfItemsToSkip();
int count = 0;
for(MyThing thing : bigList){
 if(count >= skip){
  //do stuff
 }
}

OR

int skip = getNumberOfItemsToSkip();
int count = 0;
//does subList maintain the order????
List<MyThing> sublist = bigList.subList(skip, bigList.size() - 1);
for(MyThing thing : sublist){
  //do stuff
}

Is there another way?

like image 411
Freiheit Avatar asked Dec 21 '22 10:12

Freiheit


1 Answers

In this case I would not use the an enhanced for loop. If you access by index, then you could simply start and end at a range that makes since.

for(int i = getNumberOfItemsToSkip(); i < bigList.size(); i++) {
  Foo foo = bigList.get(i);
}
like image 95
JustinKSU Avatar answered Apr 27 '23 22:04

JustinKSU