Java iterator. Iterate over the list and save removing element from collection.

11/05/2014 14:52 | Java, Uncategorized

System: OS: OS X 10.9

What does an iterator and why we need to use them? When we need them? How to remove element from list while iterating?

Java implementations of iterators like collection interface for save looping through collection. In a practice the best situation where you can apply iterator are removing element from list.

For example try to run this code:

Result of such code will be an error:

That is happened because in the code we tried to remove element from the list while lopping through this list. To solve this problem and work with collections safety we can use iterator.
Good practice to remove element from list looks like this:

How it works?

  • Firstly we defining iterator for collection: Iterator iterator = list.iterator();
  • For loop through iterator better to use while loop: while (iterator.hasNext())
  • To get next element in a list use: iterator.next();
  • All operation what you will do with element will automatically reflected in original list. In our case iterator.remove(); means that we are removing current element from the list. Finally after this while loop we will get list collection without “item2” element.

Also using iterators can be applicable for anther scenarios where you want modify original collection safely.

© 2014 Artem Gryn personal blog