Loop and remove element from a TreeSet in Java

Description

The following code shows how to loop and remove element from a TreeSet.

Example


/*ww  w.j  a v  a 2  s.c om*/


import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;

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

    // Add Items to the TreeSet
    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("TreeSet 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("\nTreeSet 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