Easy Tutorial
❮ Number Equals Java String Concat ❯

Java Example - Removing Specified Element from Collection

Java Example

The following example demonstrates how to use the collection.remove() method of the Collection class to remove a specified element from a collection:

Main.java File

import java.util.*;

public class Main {
   public static void main(String [] args) {   
      System.out.println("Collection Example!\n"); 
      int size;
      HashSet collection = new HashSet();
      String str1 = "Yellow", str2 = "White", str3 = "Green", str4 = "Blue";  
      Iterator iterator;
      collection.add(str1);    
      collection.add(str2);   
      collection.add(str3);   
      collection.add(str4);
      System.out.print("Collection Data: ");  
      iterator = collection.iterator();     
      while (iterator.hasNext()){
         System.out.print(iterator.next() + " ");  
      }
      System.out.println();
      collection.remove(str2);
      System.out.println("After removal [" + str2 + "]\n");
      System.out.print("Current Collection Data: ");
      iterator = collection.iterator();     
      while (iterator.hasNext()){
         System.out.print(iterator.next() + " ");  
      }
      System.out.println();
      size = collection.size();
      System.out.println("Collection Size: " + size + "\n");
   }
}

The output of the above code is:

Collection Example!

Collection Data: White Yellow Blue Green 
After removal [White]

Current Collection Data: Yellow Blue Green 
Collection Size: 3

Java Example

❮ Number Equals Java String Concat ❯