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:


Iterator and Iterable:
* Using the raw iterator

Table Of Contents
8 Arrays
10 Maps
11 Strings
25 JAXB
29 Enums
32 Audio
38 Iterator and Iterable
41 Scanner
63 Logging
75 Lists
78 Sets
89 JAX-WS
96 XJC
98 Process
106 Modules
114 Applets
122 JNDI
139 JavaBean
141 Literals
144 Packages
150 JMX
153 JShell
159 Sockets
167 Enum Map
175 Hashtable
177 SortedMap