Eugene
Eugene

Reputation: 60184

Skip the first item while iteration through List

I need to skip the very first item iterating through the List.

for (MyClass myObject : myList) {
    myObject.doSomething();
}

Upvotes: 2

Views: 10211

Answers (3)

rogerdpack
rogerdpack

Reputation: 66751

Something like:

for (MyClass myObject : myList.subList(1, myList.size()) {
       myObject.doSomething();
}

though I think it might not work if your list doesn't have at least one item...

Upvotes: 29

jrad
jrad

Reputation: 3190

If you use a regular for loop you can do it like this:

int size = myList.size();
for (int i = 1; i < size; i++) {
    myList.get(i).doSomething();
}

or inline:

for (int i = 1; i < myList.size(); i++) {
    myList.get(i).doSomething();
}

Upvotes: 11

Reimeus
Reimeus

Reputation: 159784

For completeness, an Iterator example:

    Iterator<MyClass> iterator = myList.iterator();
    if (iterator.hasNext()) {
        iterator.next();
    }

    while (iterator.hasNext()) {
        iterator.next().doSomething();
    }

Upvotes: 6

Related Questions