YouTip LogoYouTip

Collection Remove

# Java Example - Removing Specified Elements from a Collection [![Image 3: Java Example](#) 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 removing [" + str2 + "]n"); System.out.print("Now the collection data is: "); 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 removing Now the collection data is: Yellow Blue Green Collection size: 3 [![Image 4: Java Example](#) Java Example](#)
← Collection IteratorThread Showall β†’