简体   繁体   中英

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();
}

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...

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();
}

For completeness, an Iterator example:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM