Home  >  Article  >  Java  >  Java Example - Delete the specified element from the collection

Java Example - Delete the specified element from the collection

黄舟
黄舟Original
2017-01-21 11:11:361313browse

The following example demonstrates how to use the collection.remove() method of the Collection class to delete specified elements in the collection:

/*
 author by w3cschool.cc
 Main.java
 */import java.util.*;public class Main {
   public static void main(String [] args) {   
      System.out.println( "集合实例!\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("集合数据: ");  
      iterator = collection.iterator();     
      while (iterator.hasNext()){
         System.out.print(iterator.next() + " ");  
      }
      System.out.println();
      collection.remove(str2);
      System.out.println("删除之后 [" + str2 + "]\n");
      System.out.print("现在集合的数据是: ");
      iterator = collection.iterator();     
      while (iterator.hasNext()){
         System.out.print(iterator.next() + " ");  
      }
      System.out.println();
      size = collection.size();
      System.out.println("集合大小: " + size + "\n");
   }}


The output result of running the above code is:

集合实例!
集合数据: White Yellow Blue Green 
删除之后 [White]
现在集合的数据是: Yellow Blue Green 
集合大小: 3

The above is the Java example - delete the content of the specified element in the collection, For more related content, please pay attention to the PHP Chinese website (www.php.cn)!



Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn