Jump to content

How to Use the Iterator Method to Remove an Element From a Collection in Java?


Linux Hint

Recommended Posts

The “iterator” method offers a safe and easy way to remove or delete specific data elements from a collection while iterating over it. It prevents the occurrence of “ConcurrentModificationException” which arises when the enhanced for loop tries to modify the collection. It stores the track of the current position and offers programmers the chance to move forward and remove the underlying elements as needed.

This blog demonstrates the process to remove an element from a collection by utilizing the iterator method.

How to Use the Iterator Method to Remove an Element From a Collection in Java?

The iterator method is unidirectional and can be used with various collection types, including “ArrayList”, “LinkedList”, etc. It offers a uniform way to remove elements from any collection that implements the “Iterable” interface.

Let us visit some examples to better understand the iterator method:

Example 1: Removing Specific Elements From the Collection Using Iterator Method

The iterator method can be utilized with “if” statements or loops to select the specified elements. And then the “remove()” method is used to perform the deletion operation as shown below:

import java.util.*;
class IterExam
{
 public static void main(String[] args)
 {
  ArrayList<Integer> demoArrLis = new ArrayList<Integer>();
  for(int i=0;i<=20;i=i+2)
  {
   demoArrLis.add(i);
  }
  Iterator<Integer> itr = demoArrLis.iterator();
  System.out.println("Provided ArrayList:");

  for(int i=0;i<demoArrLis.size();i++)
   {
    System.out.print(demoArrLis.get(i)+" ");
   }
   while(itr.hasNext())
   {
    if(itr.next()%3==0)
    itr.remove();
   }
   System.out.println("\nAfter Removing Odd ArrayList Elements");
  for(int i=0;i<demoArrLis.size();i++)
    {
     System.out.print(demoArrLis.get(i)+" ");
    }
  }
}

Description of the above code:

  • First, the ArrayList is created and then a multiple of “2” is inserted till the range of “20” with the help of the “for” loop.
  • Next, declare an “iterator” method object to display the elements of ArrayList on the console.
  • Then, utilize the “hasNext()” method with the iterator object to traverse through all residing ArrayList elements.
  • After that, the “if” statement is utilized to check the elements that are fully divisible by “3” inside it.
  • Then, the “remove()” method is used to delete the elements that are returned by the “if” statement.
  • In the end, the updated ArrayList has been displayed using the “for” loop.

After the compilation:

image1-28.png

The output displays the specific elements, which are divisible by three and removed from the ArrayList using an iterator method.

Example 2: Removing All Elements From the Collection

To remove all residing elements of the collection, the iterator method can be used along with its “remove()” method as shown below:

import java.util.*;
class Emptiness
{
 public static void main(String arg[])
 {
 Vector<Integer> testVector=new Vector<Integer>();
  testVector.add(18);
  testVector.add(21);
  testVector.add(25);
  testVector.add(27);
  testVector.add(30);

 Iterator<Integer> traverse = testVector.iterator();
  System.out.print("Existing elements:");
  while(traverse.hasNext())
   System.out.print(traverse.next()+" ");
   System.out.print("\nThe testVector contains "+testVector.size()+" elements ");
  traverse = testVector.iterator();
  while(traverse.hasNext())
  {
   System.out.print("\nremoving "+traverse.next());
   traverse.remove();
  }
  System.out.println("\nNow, the testVector contains "+testVector.size()+" elements");
 }
}

Description of code:

  • First, declare and initialize “Vector” with dummy integer type values using the “add()” method.
  • Next, create an iterator method that uses the “hasNext()” and “next()” methods. It displays the residing data elements and their corresponding size.
  • Then, utilize the “hasNext()” property along the iterator object inside the “while” loop.
  • After that, utilize the “next()” method to select the upcoming element, and then, the remove() method is called to delete each receiving element.
  • In this way, all elements of the Vector are removed and the size of the Vector is displayed on the console.

Description of code:

image3-20.png

The above code confirms that all elements from the collection have been removed.

Example 3: Removing Element Using ListIterator

The ListIterator works similarly to the iterator method. The ListIterator performs traversing on both sides in the forward and backward directions. To remove specific elements from the collection using the ListIterator in Java, visit the below code:

import java.util.ArrayList;
import java.util.ListIterator;
public class ListIteratorDemo {

 //Initializing the main() method
 public static void main(String[] args)
 { //Declaring and Initializing the ArrayList
  ArrayList<String> alist = new ArrayList<String>();
  alist.add("Hoodie");
  alist.add("Polo");
  alist.add("Henleys");
  alist.add("Sweat");
  alist.add("Casual");
  alist.add("Luxury");
  alist.add("Dryfit");


  ListIterator<String> litr = alist.listIterator();
   System.out.println("List before removal");
  for (int i = 0; i < alist.size(); i++)
   System.out.print(alist.get(i) + " ");
  while (litr.hasNext()) {
   if (litr.next().equals("Sweat")) {
    litr.remove();
   }
 }
 System.out.println("\nList after removal");
  for (int i = 0; i < alist.size(); i++)
   System.out.print(alist.get(i) + " ");
  }
}

Description of the above code:

  • First, declare and initialize the ArrayList with the dummy String type values and display all elements on the console using the “for” loop.
  • Next, create an object which calls the “hasNext()” method inside the “while” loop. It traverses through all residing elements.
  • Then, the “if” statement is used that checks each element with specific text, when that element matches the “remove()” method is called. It deletes the specific element from the “aList” named ArrayList.
  • In the end, display the modified ArrayList on the console.

After compilation:

image2-26.png

The snapshot confirms the specified data element has been removed from the collection using ListIterator.

Conclusion

To remove the element from a collection, the “remove()” method of the iterator is utilized. The iterator traverses through the ArrayList to find the targeted data. Once it is found the “remove()” method is used to remove that specific data element. It offers a standardized technique across different collections and prevents issues and the occurrence of several exceptions like “ConcurrentModificationException”. Along with it, the “ListIterator” can also be helpful.

View the full article

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...