Remove element from HashSet in Java

Description

The following code shows how to remove element from HashSet.

Example


//ww  w  . j  a  v  a 2 s  . c  o  m
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class Main {
  public static void main(String[] args) {
    Set<Integer> set = new HashSet<Integer>();

    set.add(new Integer(1));
    set.add(new Integer(2));
    set.add(new Integer(3));
    set.add(new Integer(4));
    set.add(new Integer(5));
    set.add(new Integer(6));
    set.add(new Integer(7));
    set.add(new Integer(8));
    set.add(new Integer(9));
    set.add(new Integer(10));

    // Use iterator to display the vsetes
    System.out.println("HashSet Before: ");
    for (Iterator i = set.iterator(); i.hasNext();) {
      Integer integer = (Integer) i.next();
      System.out.println(integer);
    }

    // Remove the integer 6
    System.out.println("\nRemove integer 6");
    set.remove(new Integer(6));

    // Use iterator to display the vsetes
    System.out.println("\nHashSet After: ");
    for (Iterator i = set.iterator(); i.hasNext();) {
      Integer integer = (Integer) i.next();
      System.out.println(integer);
    }

  }
}

The code above generates the following result.





















Home »
  Java Tutorial »
    Java Collection »




Java ArrayList
Java Collection
Java Comparable
Java Comparator
Java HashMap
Java HashSet
Java Iterator
Java LinkedHashMap
Java LinkedHashSet
Java LinkedList
Java List
Java ListIterator
Java Map
Queue
Java Set
Stack
Java TreeMap
TreeSet