Java tutorial to remove an element from collection using Iterator object. Here, we will discuss about the methods to remove an element from a collection using iterator objects in Java alongside suitable examples and sample outputs. Also we have discussed what is an Iterator in brief. The methods are as follows:
- Removing All Elements.
- Removing A Specific Element
- Removing Using List Iterator
- Removing From An ArrayList Collection
If you have any doubts or suggestions related to remove an element from collection using Iterator, leave a comment here.
What is an Iterator?
We can understand Iterator as a mechanism used to travel through an entity. It iterates (loops) through the elements of the collection. While iterating, it touches (accesses) each element and allows us to perform any required activity on that element.
The collection can be an ArrayList, a LinkedList, a HashSet, a Vector or any other such thing that holds a set of elements. All collection classes provide an Iterator so that we can travel through them.
Normally we travel through an array by taking a variable (like i) starting from 0th location to last location as in the following example.
1 2 3 4 |
for(int i=0; i<n; i++) { //some stuff } |
If n value is 10, then the loop will travel for 10 times (where ‘i’ value will be 0, 1, 2, …. 9) and each time some operation is done on ith element.
The iterator is also used for similar purpose where we travel through a collection where we perform an activity on each element of the collection.
Iterator will take care of counting the number of elements in the collection, incrementing the loop counter, etc. Iterator holds a layer on such loop (mentioned above) and abstracts what happens inside from us.
How to remove an element from collection using iterator object?
Removing all elements From Collection
The Iterator interface has a method named remove() and we can use that method to remove an element from a collection. In the following example we can see the Iterator working on a Vector collection. It removes all the 5 elements of the Vector.
For Example:
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 |
import java.util.*; class Check { public static void main(String arg[]) { Vector<Integer> v=new Vector<Integer>(); v.add(10); v.add(20); v.add(30); v.add(40); v.add(50); Iterator<Integer> iter = v.iterator(); System.out.print("Existing elements:"); while(iter.hasNext()) System.out.print(iter.next()+" "); System.out.print("\nthe vector has "+v.size()+" elements "); iter = v.iterator(); while(iter.hasNext()) { System.out.print("\nremoving "+iter.next()); iter.remove(); } System.out.println("\nNow, the vector has "+v.size()+" elements"); } } |
Output:
1 2 3 4 5 6 7 8 |
Existing elements:10 20 30 40 50 the vector has 5 elements removing 10 removing 20 removing 30 removing 40 removing 50 the vector has 0 elements |
In the above example, we have created a Vector object that can hold Integers and added 5 elements (10, 20, 30, 40 and 50) to the Vector.
Then we have created an Iterator for travelling through the Vector. The iterator() method of the Vector gives the Iterator to us. Then traveled throw the Vector object (hasNext() lets us know whether there are any more elements in the Vector and next() gives access to the next available element).
By that time the Vector object has 5 elements. Then, we started travelling again from begin (by taking the Iterator again) and kept removing elements one by one using remove(). After removing all the 5 elements, the size of the Vector is 0.
Removing a specific element
1 2 3 4 5 6 7 |
iter = v.iterator(); for(int i=1;iter.hasNext();i++) { iter.next(); if(i==3) iter.remove(); } |
In the above example, we have travelled through the Vector and accessed all the elements but removed only the third element.
So after the loop completes the value 30 would not be existing (see above in the complete program, we have added 10, 20, 30, 40 and 50 into the Vector) and the remaining 4 values (10, 20, 40 and 50) will be available.
Remove using List Iterator
Similar to the way we use Iterator, we can also use ListIterator to remove an element. In the following example we can observe that. Here, we are taking an integer (that represents the index of the element to be removed) from the use and removing the element at that position.
For Example:
1 2 3 4 5 6 7 8 9 10 11 |
System.out.print("element at which position you want to remove:"); int n=scanner.nextInt(); ListIterator<Integer> iter = v.listIterator(); for(int i=1;iter.hasNext();i++) { iter.next(); if(i==n) //we want to remove nth element { iter.remove(); } } |
The same mechanism can be applied to remove elements from ArrayList, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet, ArrayDeque, etc. an example of removing from ArrayList is given below.
Removing element from an ArrayList collection
Removing element from an ArrayList using Iterator is same as removing from a Vector.
The ArrayList also gives reference of Iterator with the method iterator(). By getting the reference we can travel through the collection (ArrayList) and remove 1 or more elements.
For Example:
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 |
import java.util.*; class Check { public static void main(String arg[]) { //creating an ArrayList object ArrayList<Integer> col=new ArrayList<Integer>(); // looping through so that 0 is placed at 0, 1 is placed at 1, 4 is placed at 2, 9 is place at 3, 16 is placed at 4 and so on… for(int i=0;i<10;i++) { col.add(i*i); System.out.println("added "+(i*i)); } // taking Iterator using the method iterator() Iterator<Integer> iter = col.iterator(); // displaying existing elements System.out.print("\nExisting elements:"); while(iter.hasNext()) System.out.print(iter.next()+" "); // displaying count of elements in the ArrayList. // looping through ArrayList so that we remove element when ‘i’ value is 3 for(int i=1;iter.hasNext();i++) { iter.next(); if(i==n) { //removing element using the method remove() iter.remove(); System.out.println("\nremoved element at location:"+n); } } // again taking Iterator reference to travel from begin to end iter = col.iterator(); // displaying the elements after removing the element. System.out.print("\nExisting elements:"); while(iter.hasNext()) System.out.print(iter.next()+" "); System.out.println("\nNow, the collection has "+col.size()+" elements"); } } |
In this example, we are adding 6 elements to the ArrayList, printed them, removed nth (3rd) element, and printed the resulting ArrayList. The outputs are obvious.
If you have any doubts related to how to remove an element from collection using iterator object, do leave a comment here or give a suggestion to improve the article.