java list iterator example
Java forEach
Since Java 8 forEach starts to be one of the prefered ways for iterating a list:
import java.util.Arrays;
import java.util.List;
List<String> myList = Arrays.asList("Java 8 is cool", "Java 9 is cool", "Java 7 is cool");
myList.forEach((item) -> {
System.out.println(item);
});
Java For Loop
The simplest and one of the most used iterators in java is for loop. You can customised it depending on your needs:
import java.util.Arrays;
import java.util.List;
List<String> myList = Arrays.asList("Java 8 is cool", "Java 9 is cool", "Java 7 is cool");
for (int i = 0; i < myList.size(); i++) {
System.out.println(myList.get(i));
}
Java iterator
Another option to iterate over a list is with: java.util.Iterator. The example below show to use it with combination with while loop.
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
List<String> myList = Arrays.asList("Java 8 is cool", "Java 9 is cool", "Java 7 is cool");
Iterator<String> myIterator = myList.iterator();
while (myIterator.hasNext()) {
System.out.println(myIterator.next());
}