Creating a Sorted Set : TreeSet « Collections Data Structure « Java






Creating a Sorted Set

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

public class Main {
  public static void main(String[] argv) {
    // Create the sorted set
    Set<String> set = new TreeSet<String>();

    set.add("b");
    set.add("c");
    set.add("a");

    Iterator it = set.iterator();
    while (it.hasNext()) {

      Object element = it.next();
      System.out.println(element);
    }

    // Create an array containing the elements in a set
    String[] array = (String[]) set.toArray(new String[set.size()]);
    Arrays.toString(array);
  }
}

   
    
  








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.Loop and remove element from a TreeSet
16.Comparable with a sorted collection.
17.A TreeSet that ensures it never grows beyond a max size.