HomeCore JavaJava Iterator guide + remove elements while iterating examples

Java Iterator guide + remove elements while iterating examples

A java Iterator interface is used to retrieve elements one by one from any collection implementation, as we can apply Iterator on any collection, it’s also called universal cursor. In addition to retrieve elements we can also remove elements from collection.

Java Enumeration interface does not support to remove elements from collection while iterating, to overcome this in Java 1.2 introduced Iterator interface as a replacement for Enumeration and also improved method names.

1. Java Iterator interface methods

  1. default void forEachRemaining(Consumer action) (Since Java 8) – Performs the given action for each remaining element until all elements have been processed or the action throws an exception.
  2. boolean hasNext() – Returns true if the iteration has more elements.
  3. E next() – Returns the next element in the iteration.
  4. default void remove() – Removes from the underlying collection the last element returned by this iterator (optional operation).

2. Iterator example using Vector and List

The following example demonstrates how to retrieve elements one by one from Vector and List using iterator.

public class JavaVectorAndListIteratorDemo {

	public static void main(String[] args) {
		
		Vector<String> v = new Vector<>();
		
		// adding single element
		v.add("Peter");//Collection interface method
		v.addElement("Martin");//Vector Specific method
		v.add(2, "Mike");//List specific method
			
		System.out.println(v); //[Peter, Martin, Mike]
		
		// Obtaining Iterator
		Iterator<String> i1 = v.iterator();
		System.out.println("------- Vector elements ------");
		while (i1.hasNext()) {
			String string = i1.next();
			System.out.println(string);
		}
		
		// Creating a List from Vector
		List<String> l = new ArrayList<>(v);
		
		// Obtaining Iterator
		Iterator<String> i2 = v.iterator();
		System.out.println("------- List elements ------");
		while (i2.hasNext()) {
			String string = i2.next();
			System.out.println(string);
		}
	}
}

Output :

[Peter, Martin, Mike]
------- Vector elements ------
Peter
Martin
Mike
------- List elements ------
Peter
Martin
Mike

3. Iterator example using Map

The following example demonstrates how to retrieve elements one by one from Map using iterator.

public class HashMapIteratorDemo {

	public static void main(String[] args) {
		Map<Integer, String> m = new HashMap<>();
		m.put(1,"A");
		m.put(2,"B");
		m.put(3,"C");
		m.put(4,"D");
		m.put(5,"E");
		m.put(6,"F");
		m.put(7,"G");
		m.put(8,"H");
		m.put(22,"I");
		m.put(0,"K");
		m.put(23,"J");
		m.put(25,"L");
		System.out.println(m);
		
		// Obtaining keys as iterator from key Set
		Iterator<Integer> i = m.keySet().iterator();
		
		while (i.hasNext()) {
			Integer key = i.next();
			System.out.println("[key"+key+", value="+m.get(key)+"]");
		}
	}
}

Output :

{0=K, 1=A, 2=B, 3=C, 4=D, 5=E, 6=F, 22=I, 7=G, 23=J, 8=H, 25=L}
[key0, value=K]
[key1, value=A]
[key2, value=B]
[key3, value=C]
[key4, value=D]
[key5, value=E]
[key6, value=F]
[key22, value=I]
[key7, value=G]
[key23, value=J]
[key8, value=H]
[key25, value=L]

4. Remove elements while iterating

The following example demonstrates how to remove elements while iterating collection using iterator.

public class RemoveElementsWhileIteratingDemo {

	public static void main(String[] args) {
		
		List<String> l = new ArrayList<>();
	
		l.add("Peter");
		l.add("Martin");
		l.add("Mike");
		l.add("John");
		l.add("Gerhard");
		System.out.println(l); //[Peter, Martin, Mike, John, Gerhard]
		
		
		Iterator<String> i = l.iterator();
		
		// Remove name if starts with "P"
		while (i.hasNext()) {
			String name = i.next();
			
		    if(!name.startsWith("P"))
		    	System.out.println(name);
		    else
		    	i.remove();
		}
		System.out.println(l);
	}
}

Output :

[Peter, Martin, Mike, John, Gerhard]
Martin
Mike
John
Gerhard
[Martin, Mike, John, Gerhard]

5. Iterator forEachRemaining Example

forEachRemaining() processes the elements from next remaining element while iterating. Following example demonstrates how forEachRemaining() method works.

public class IteratorForEachRemainingDemo {

	public static void main(String[] args) {
		
		List<String> l = new ArrayList<>();
	
		l.add("Peter");
		l.add("Martin");
		l.add("Mike");
		l.add("John");
		l.add("Gerhard");
		System.out.println(l); //[Peter, Martin, Mike, John, Gerhard]
		
		Iterator<String> i = l.iterator();
		
		// Remove name if starts with "P"
		while (i.hasNext()) {
			String name = i.next();
			
		    if(name.startsWith("P"))
		    	System.out.println(name);
		    else
		    	i.forEachRemaining(System.out::println);

                    //Consumer<String> c = s -> System.out.println(s);
		    //i.forEachRemaining(c);
		}
	}
}
[Peter, Martin, Mike, John, Gerhard]
Peter
Mike
John
Gerhard

6. Limitations in Iterator

Iterator is a universal cursor, it can be used to retrieve elements from any collection, but it has some limitations. We can remove but can not add or update elements while iterating collections, and we can not navigate forward and backward direction to get previous and next elements or indexes. To achieve this limitation by using Java ListIterator, but note that we can apply only for list implemented classes.

7. Conclusion

In this article we have covered about java Iterator, and methods of it by demonstrating with examples and removing elements from Collection while iterating.

References

  1. Java Document
  2. Java 8 Consumer
  3. Java Enumeration interface

LEAVE A REPLY

Please enter your comment!
Please enter your name here