Using the raw iterator

suggest change

While using the foreach loop (or “extended for loop”) is simple, it’s sometimes beneficial to use the iterator directly. For example, if you want to output a bunch of comma-separated values, but don’t want the last item to have a comma:

List<String> yourData = //...
Iterator<String> iterator = yourData.iterator();
while (iterator.hasNext()){
    // next() "moves" the iterator to the next entry and returns it's value.
    String entry = iterator.next();
    System.out.print(entry);
    if (iterator.hasNext()){
        // If the iterator has another element after the current one:
        System.out.print(",");
    }
}

This is much easier and clearer than having a isLastEntry variable or doing calculations with the loop index.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents