Loop and remove element from a TreeSet : TreeSet « Collections Data Structure « Java






Loop and remove element from a TreeSet

   

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

public class TreeSetExample {
  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);
    }

  }
}

   
    
    
  








Related examples in the same category

1.Add values to TreeSet
2.TreeSet, SortedSet and HashSet
3.Get Synchronized Set from Java TreeSet example
4.Check if a particular value exists in Java TreeSet example
5.Copy all elements of Java TreeSet to an Object Array Example
6.Get Head Set from Java TreeSet example
7.Get lowest and highest value stored in Java TreeSet
8.Get Size of Java TreeSet
9.Get Sub Set from Java TreeSet
10.Get Tail Set from Java TreeSet
11.Iterate through elements of Java TreeSet
12.Remove all elements from Java TreeSet
13.Remove specified element from Java TreeSet
14.Sort items in a Set
15.Creating a Sorted Set
16.Comparable with a sorted collection.
17.A TreeSet that ensures it never grows beyond a max size.