How to start an iteration through a collection not from the very beginning

I want the iteration to skip the first few elements. elementsis List<WebElement>. I would like to iterate over the list not from the very beginning, but starting from somewhere in the middle, how could I do this?

for ( WebElement element : elements )
{
      //block of code
}
+5
source share
5 answers

In many cases, when you want to apply some operation to a certain range List, you can usesubList() :

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

This is also great for removing some range:

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

Please note that subListonly exists on List, so this will not work on objects Setor other non-List Collection.

+13
source

elements - , listIterator, elements.listIterator(index). , index.

:

for(ListIterator iter = elements.listIterator(2);iter.hasNext;) {
  WebElement element = (WebElement)iter.next;
  ...
}

elements , , .

+9

List.listIterator(int),

    List<WebElement> list = ...
    for(Iterator<WebElement> i = list.listIterator(1); i.hasNext();) {
        WebElement next = i.next();
    }

for(int i = 1; i < list.size(); i++) {
     WebElement e = list.get(i);
}

, # 1 LinkedList # 2 ArrayList. java.util.RandomAccess, , .

+4

?

int i = 0;
for (WebElement element : elements)
{
      if (/*i++ satisfies some condition*/) {
          //block of code
      }
}

, : for-loop.

, , , .

+2

You can use arraylist if you want to reference, or make your own, so to speak. This will allow you to access the points by reference (for example, an array), after which you can iterate through the general while (node.hasNext ()) {...} to the end.

0
source

All Articles