Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to start iterating through a collection not from the beginning

I want the iteration to skip the first few elements. elements is a List<WebElement>. I would like to iterate through the list not from the beginning, but starting from somewhere in the middle, how could I do that?

for ( WebElement element : elements )
{
      //block of code
}
like image 425
Code Enthusiastic Avatar asked Jan 21 '13 12:01

Code Enthusiastic


1 Answers

For many cases where you want to apply some operation to a specific range of List, you can use subList():

for (WebElement element : elements.subList(3, 7)) {
  // do stuff
}

This also works fine for removing some range:

myList.subList(4, 14).clear();

Note that subList only exists on List, so this won't work on a Set or other non-List Collection objects.

like image 90
Joachim Sauer Avatar answered Oct 25 '22 17:10

Joachim Sauer