Reputation: 2847
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
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
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
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
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
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