The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > java.util  [50 examples] > Sorted Collections  [5 examples]

e358. Creating a Sorted Set

A sorted set is a set that maintains its elements in a sorted order. Inserts and retrievals are more expensive in a sorted set but iterations over the set is always in order.

See also e352 Creating a Set.

    // Create the sorted set
    SortedSet set = new TreeSet();
    
    // Add elements to the set
    set.add("b");
    set.add("c");
    set.add("a");
    
    // Iterating over the elements in the set
    Iterator it = set.iterator();
    while (it.hasNext()) {
        // Get element
        Object element = it.next();
    }
    // The elements are iterated in order: a, b, c
    
    // Create an array containing the elements in a set (in this case a String array).
    // The elements in the array are in order.
    String[] array = (String[])set.toArray(new String[set.size()]);

 Related Examples
e359. Sorting an Array
e360. Finding an Element in a Sorted Array
e361. Finding an Element in a Sorted List
e362. Inserting an Element into a Sorted List

See also: Arrays    Bits    Collections    Dates    Hash Tables    Lists    Property Files    Sets    Time    Timers   


© 2002 Addison-Wesley.