Java Iterator tutorial with examples will help you to understand how to use the Java Iterator in an easy way. Iterator interface in Java is a member of the Java Collection Framework. Java Iterator is used to iterate over a collection to retrieve its elements.
Unlike Enumeration, the Iterator in Java allows us to remove elements from the underlying collection while iterating over the elements of the collection.
How to iterate over a Collection using the Iterator?
The Iterator in Java defines three main methods. The hasNext
method returns boolean depending upon whether there are more elements to iterate over in the collection. The next
method returns the next element of the collection. The remove
method removes the current element from the underlying collection.
The iterator
method is used to get the Iterator for the collection class, for example, implementations of Set and List interfaces. Here is how to iterate over a collection.
- Get the iterator object for the collection by calling the
iterator
method. - Loop until the Iterator’s
hasNext
method returns true. - Inside the loop, call the
next
method of the Iterator to get the current element of the collection.
The below given code snippet shows how to iterate over an ArrayList using an iterator.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
ArrayList aListDays = new ArrayList<String>(); aListDays.add("Sunday"); aListDays.add("Monday"); aListDays.add("Tuesday"); /* * get the iterator by using iterator method * of ArrayList class */ Iterator iterator = aListDays.iterator(); /* * loop through elements till iterator's * hasNext method returns true. */ while( iterator.hasNext() ){ /* * get the next element using * next method */ System.out.println( iterator.next() ); } |
Output
1 2 3 |
Sunday Monday Tuesday |
Important note:
Do not call the next
method without first checking whether the collection has more elements using the hasNext
method. Also, do not call the next
method multiple times inside the loop to make sure that there will always an element. The next
method will throw NoSuchElementException if there are no elements to iterate.
Consider below given code snippet.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
import java.util.ArrayList; import java.util.Iterator; import java.util.List; class Student{ private String name; private int marks; public Student(String name, int marks){ this.name = name; this.marks = marks; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getMarks() { return marks; } public void setMarks(int marks) { this.marks = marks; } } public class Demo { public static void main(String args[]){ List<Student> listStudents = new ArrayList<Student>(); listStudents.add( new Student("Ryan", 70) ); listStudents.add( new Student("Tanya", 84) ); listStudents.add( new Student("Tina", 65) ); listStudents.add( new Student("John", 43) ); listStudents.add( new Student("Shawn", 58) ); Iterator<Student> iterator = listStudents.iterator(); while(iterator.hasNext()){ System.out.println( iterator.next().getName() + " " + iterator.next().getMarks() ); } } } |
What do you think the output would be? If you think that the code will print names and marks for all the students, you are wrong. Here is the output of the code.
1 2 3 4 5 |
Ryna 84 Tina 43 Exception in thread "main" java.util.NoSuchElementException at java.util.ArrayList$Itr.next(Unknown Source) at Demo.main(Demo.java:45) |
The code prints the name of the first student followed by the marks of the second student. Again, it prints the name of the third student and the marks of the fourth student. It is because we have called the next
method twice in the loop. When you call the next
method on the iterator object, it returns the next element of the collection. When the iterator is on the fifth element, we call the next
method and since there are no more objects in the collection, the code throws NoSuchElementException
.
Here is how the above code should be written.
1 2 3 4 5 6 7 8 |
Iterator<Student> iterator = listStudents.iterator(); Student student = null; while(iterator.hasNext()){ student = iterator.next(); System.out.println( student.getName() + " " + student.getMarks() ); } |
Output
1 2 3 4 5 |
Ryan 70 Tanya 84 Tina 65 John 43 Shawn 58 |
Also, there should be one next
method call per hasNext
method to avoid NoSuchElementException
.
How to iterate over ArrayList in Java?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
ArrayList<Integer> aListNumbers = new ArrayList<Integer>(); aListNumbers.add(1); aListNumbers.add(2); aListNumbers.add(3); //get the Iterator using iterator method of ArrayList Iterator<Integer> iterator = aListNumbers.iterator(); System.out.println("Iterate through ArrayList elements"); while( iterator.hasNext() ){ System.out.println( iterator.next() ); } |
Output
1 2 3 4 |
Iterate through ArrayList elements 1 2 3 |
Please visit the ArrayList tutorial to know more about ArrayList.
How to iterate over LinkedList in Java?
1 2 3 4 5 6 7 8 9 10 11 12 13 |
LinkedList<String> linkedListColors = new LinkedList<String>(); linkedListColors.add("Red"); linkedListColors.add("Green"); linkedListColors.add("Blue"); //iterator method of the LinkedList Iterator<String> iterator = linkedListColors.iterator(); System.out.println("Iterate through LinkedList elements"); while( iterator.hasNext() ){ System.out.println( iterator.next() ); } |
Output
1 2 3 4 |
Iterate through LinkedList elements Red Green Blue |
Please visit the LinkedList tutorial to know more about LinkedList.
How to iterate over TreeSet in Java?
1 2 3 4 5 6 7 8 9 10 11 12 13 |
TreeSet<Integer> tSetOddNumbers = new TreeSet<Integer>(); tSetOddNumbers.add(5); tSetOddNumbers.add(1); tSetOddNumbers.add(3); //get the iterator using iterator method of TreeSet Iterator<Integer> iterator = tSetOddNumbers.iterator(); System.out.println("Iterate through TreeSet elements"); while( iterator.hasNext() ){ System.out.println( iterator.next() ); } |
Output
1 2 3 4 |
Iterate through TreeSet elements 1 3 5 |
Please visit the TreeSet tutorial to know more about TreeSet.
How to iterate over HashSet in Java?
1 2 3 4 5 6 7 8 9 10 11 12 13 |
HashSet<Integer> hSetEvenNumbers = new HashSet<Integer>(); hSetEvenNumbers.add(6); hSetEvenNumbers.add(2); hSetEvenNumbers.add(4); //get the iterator using iterator method of HashSet Iterator<Integer> iterator = hSetEvenNumbers.iterator(); System.out.println("Iterate through HashSet elements"); while( iterator.hasNext() ){ System.out.println( iterator.next() ); } |
Output
1 2 3 4 |
Iterate through HashSet elements 2 4 6 |
Please visit the HashSet tutorial to know more about HashSet.
How to iterate over HashMap in Java?
Iterator through keys of HashMap
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
HashMap<Integer, String> hMapNumbers = new HashMap<Integer, String>(); hMapNumbers.put(1, "One"); hMapNumbers.put(2, "Two"); hMapNumbers.put(3, "Three"); /* * Iterate through all keys of HashMap */ //get the key set using the keySet method Set<Integer> keys = hMapNumbers.keySet(); //get the iterator using the iterator method Iterator<Integer> iterator = keys.iterator(); System.out.println("Iterate through keys of HashMap"); while( iterator.hasNext() ){ System.out.println( iterator.next() ); } |
Output
1 2 3 4 |
Iterate through keys of HashMap 1 2 3 |
Iterator through values of HashMap
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
HashMap<Integer, String> hMapNumbers = new HashMap<Integer, String>(); hMapNumbers.put(1, "One"); hMapNumbers.put(2, "Two"); hMapNumbers.put(3, "Three"); /* * Iterate through all values of HashMap */ //get all values of HashMap using the values method Collection<String> values = hMapNumbers.values(); //get the iterator using the iterator method Iterator<String> iterator = values.iterator(); System.out.println("Iterate through values of HashMap"); while( iterator.hasNext() ){ System.out.println( iterator.next() ); } |
Output
1 2 3 4 |
Iterate through values of HashMap One Two Three |
Iterate through key-value mappings of HashMap
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
HashMap<Integer, String> hMapNumbers = new HashMap<Integer, String>(); hMapNumbers.put(1, "One"); hMapNumbers.put(2, "Two"); hMapNumbers.put(3, "Three"); /* * Iterate through all key value mappings of HashMap */ //get all mappings of HashMap using the entrySet method Set<Map.Entry<Integer, String>> entrySet = hMapNumbers.entrySet(); //get the iterator using the iterator method Iterator<Map.Entry<Integer, String>> iterator = entrySet.iterator(); System.out.println("Iterate through mappings of HashMap"); while( iterator.hasNext() ){ Map.Entry<Integer, String> entry = iterator.next(); System.out.println( entry.getKey() + " => " + entry.getValue() ); } |
Output
1 2 3 4 |
Iterate through mappings of HashMap 1 => One 2 => Two 3 => Three |
Please visit the HashMap tutorial to know more about HashMap.
How to iterate over an TreeMap in Java?
Iterator through keys of TreeMap
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
TreeMap<Integer, String> tMapOddNumbers = new TreeMap<Integer, String>(); tMapOddNumbers.put(1, "One"); tMapOddNumbers.put(3, "Three"); tMapOddNumbers.put(5, "Five"); /* * Iterate through all keys of TreeMap */ //get the key set using the keySet method Set<Integer> keys = tMapOddNumbers.keySet(); //get the iterator using the iterator method Iterator<Integer> iterator = keys.iterator(); System.out.println("Iterate through keys of TreeMap"); while( iterator.hasNext() ){ System.out.println( iterator.next() ); } |
Output
1 2 3 4 |
Iterate through keys of TreeMap 1 3 5 |
Iterator through values of TreeMap
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
TreeMap<Integer, String> tMapOddNumbers = new TreeMap<Integer, String>(); tMapOddNumbers.put(1, "One"); tMapOddNumbers.put(3, "Three"); tMapOddNumbers.put(5, "Five"); /* * Iterate through all values of TreeMap */ //get all values of TreeMap using the values method Collection<String> values = tMapOddNumbers.values(); //get the iterator using the iterator method Iterator<String> iterator = values.iterator(); System.out.println("Iterate through values of TreeMap"); while( iterator.hasNext() ){ System.out.println( iterator.next() ); } |
Output
1 2 3 4 |
Iterate through values of TreeMap One Three Five |
Iterate through key-value mappings of HashMap
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
TreeMap<Integer, String> tMapOddNumbers = new TreeMap<Integer, String>(); tMapOddNumbers.put(1, "One"); tMapOddNumbers.put(3, "Three"); tMapOddNumbers.put(5, "Five"); /* * Iterate through all key value mappings of TreeMap */ //get all mappings of TreeMap using the entrySet method Set<Map.Entry<Integer, String>> entrySet = tMapOddNumbers.entrySet(); //get the iterator using the iterator method Iterator<Map.Entry<Integer, String>> iterator = entrySet.iterator(); System.out.println("Iterate through mappings of TreeMap"); while( iterator.hasNext() ){ Map.Entry<Integer, String> entry = iterator.next(); System.out.println( entry.getKey() + " => " + entry.getValue() ); } |
Output
1 2 3 4 |
Iterate through mappings of TreeMap 1 => One 3 => Three 5 => Five |
Please visit the TreeMap tutorial to know more about TreeMap.
How to iterate over an LinkedMap in Java?
Iterator through keys of LinkedHashMap
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
LinkedHashMap<Integer, String> lhMapEvenNumbers = new LinkedHashMap<Integer, String>(); lhMapEvenNumbers.put(2, "Two"); lhMapEvenNumbers.put(4, "Four"); lhMapEvenNumbers.put(6, "Six"); /* * Iterate through all keys of LinkedHashMap */ //get the key set using the keySet method Set<Integer> keys = lhMapEvenNumbers.keySet(); //get the iterator using the iterator method Iterator<Integer> iterator = keys.iterator(); System.out.println("Iterate through keys of LinkedHashMap"); while( iterator.hasNext() ){ System.out.println( iterator.next() ); } |
Output
1 2 3 4 |
Iterate through keys of LinkedHashMap 2 4 6 |
Iterator through values of LinkedHashMap
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
LinkedHashMap<Integer, String> lhMapEvenNumbers = new LinkedHashMap<Integer, String>(); lhMapEvenNumbers.put(2, "Two"); lhMapEvenNumbers.put(4, "Four"); lhMapEvenNumbers.put(6, "Six"); /* * Iterate through all values of LinkedHashMap */ //get all values of LinkedHashMap using the values method Collection<String> values = lhMapEvenNumbers.values(); //get the iterator using the iterator method Iterator<String> iterator = values.iterator(); System.out.println("Iterate through values of LinkedHashMap"); while( iterator.hasNext() ){ System.out.println( iterator.next() ); } |
Output
1 2 3 4 |
Iterate through values of LinkedHashMap Two Four Six |
Iterate through key-value mappings of LinkedHashMap
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
LinkedHashMap<Integer, String> lhMapEvenNumbers = new LinkedHashMap<Integer, String>(); lhMapEvenNumbers.put(2, "Two"); lhMapEvenNumbers.put(4, "Four"); lhMapEvenNumbers.put(6, "Six"); /* * Iterate through all key value mappings of LinkedHashMap */ //get all mappings of LinkedHashMap using the entrySet method Set<Map.Entry<Integer, String>> entrySet = lhMapEvenNumbers.entrySet(); //get the iterator using the iterator method Iterator<Map.Entry<Integer, String>> iterator = entrySet.iterator(); System.out.println("Iterate through mappings of LinkedHashMap"); while( iterator.hasNext() ){ Map.Entry<Integer, String> entry = iterator.next(); System.out.println( entry.getKey() + " => " + entry.getValue() ); } |
Output
1 2 3 4 |
Iterate through mappings of LinkedHashMap 2 => Two 4 => Four 6 => Six |
Please visit the LinkedHashMap tutorial to know more about LinkedHashMap.
How to remove elements using the Iterator?
The remove
method of the Iterator class removes the current element from the collection.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
ArrayList<String> aListColors = new ArrayList<String>(); aListColors.add("Red"); aListColors.add("Green"); aListColors.add("Blue"); Iterator<String> iterator = aListColors.iterator(); String color = null; while(iterator.hasNext()){ color = iterator.next(); if(color.equalsIgnoreCase("green")){ //remove element from collection using remove method iterator.remove(); } } System.out.println("ArrayList contains: "); System.out.println(aListColors); |
Output
1 2 |
ArrayList contains: [Red, Blue] |
Note: The remove
method throws IllegalStateException
if,
- The
remove
method is called before the first call of thenext
method. - The
remove
method is called the second time for the same element.
Also remove
method is not supported by all the collections. If you call the remove
method on a collection which does not support the remove operation, it will throw UnsupportedOperationException
.
For example, the list obtained by converting an array object using the asList
method of the Arrays class does not support the remove operation.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
String[] strColors = {"Red", "Green", "Blue"}; List<String> listColors = Arrays.asList(strColors); Iterator<String> iterator = listColors.iterator(); String color = null; while(iterator.hasNext()){ color = iterator.next(); if(color.equalsIgnoreCase("green")){ iterator.remove(); } } |
Output
1 2 3 4 |
Exception in thread "main" java.lang.UnsupportedOperationException at java.util.AbstractList.remove(Unknown Source) at java.util.AbstractList$Itr.remove(Unknown Source) at Demo.main(Demo.java:64) |
Below given are additional Java iterator examples that discuss topics in more detail.
Java Iterator Examples
- How to iterate over ArrayList using Iterator
- How to iterate through List using Iterator
- How to iterate through HashMap using Iterator
- Java ArrayList Iterator
- How to iterate ArrayList in reverse order
- Java TreeMap iterate using Iterator
- Java TreeMap iterate in reverse order using Iterator
- Java Iterate HashSet
- Java Iterate TreeSet
- Java Iterate TreeSet in reverse order
- Java Iterate LinkedHashSet
- Java Iterate Vector
References:
Java Iterator interface Javadoc
Please let me know if you liked the Java Iterator tutorial with examples in the comments section below.