Code Enthusiastic
Code Enthusiastic

Reputation: 2847

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
}

Upvotes: 11

Views: 10492

Answers (5)

Hui Zheng
Hui Zheng

Reputation: 10224

Why not just use simplest and most straightforward way?

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

Or, more native way: keep track of index in an unenhanced for-loop.

Other way like creating sublist looks fancier, but that will take more time and space.

Upvotes: 3

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136042

You can use List.listIterator(int) as in this example

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

or simply

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

note that #1 is faster with LinkedList and #2 is faster with ArrayList. There is a special marker interface java.util.RandomAccess to determine which version is more efficient for a given List.

Upvotes: 5

corvid
corvid

Reputation: 11187

You could use an arraylist if you want to reference, or make your own, so to speak. This will let you access points by reference (like an array) then you can iterate through with a generic while(node.hasNext()) {...} to the end.

Upvotes: 0

pushy
pushy

Reputation: 9635

If elements is a List, you could use the listIterator, specifically the method elements.listIterator(index). It will return a list iterator starting at the element at index.

E.g:

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

If elements is not a list, you still could use that approach by creating a new list with the contents of your collection.

Upvotes: 10

Joachim Sauer
Joachim Sauer

Reputation: 308051

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.

Upvotes: 17

Related Questions