Iterators in Java
- Eclipse: Oxygen
- Java: 1.8
The list of iterators in Java is shown here. The iterators are the same as for the foreach loop and do not have any additional features compared to the foreach loop. The list iterators have some interesting features like the previous one and more, which will be seen later.
In the following example, Iterator is used for iterating in the list. hasNext() method of iterator check for next element in the collection and next() method returns the current element.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
public class App { public static void main(String[] args) { List<String> countries = new LinkedList<>(); countries.add("India"); countries.add("USA"); countries.add("Poland"); countries.add("Egypt"); countries.add("Thailand"); countries.add("Russia"); new App().printList(countries); } void printList(List<String> list){ ListIterator<String> iterator = list.listIterator(); while(iterator.hasNext()){ System.out.println("Element: "+iterator.next()); } } } |
Output
1 2 3 4 5 6 7 8 9 10 11 |
Element: India Element: USA Element: Poland Element: Egypt Element: Thailand Element: Russia |
Contributed by: Poonam Tomar