Java Examples - Remove a Specified Element from a Collection
The following example demonstrates how to use the collection.remove() method of the Collection class to remove the 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 deletion [" + 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 running the above code is:
集合实例! 集合数据: White Yellow Blue Green 删除之后 [White] 现在集合的数据是: Yellow Blue Green 集合大小: 3Other Extensions
Java Examples