Creating a Sorted Set

A sorted set is a set that maintains its items 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 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()]);

Comments

8 Jul 2010 - 8:51am by Chaim (not verified)

Very useful. Answered my question (as a relatively inexperienced Java user) immediately. Must a SortedSet be initialized to a new TreeSet? I know the API says that TreeSet is a known implementation of a SortedSet, but does that mean the SortedSet must be initialized this way?

18 Aug 2010 - 10:50pm by Travis Smith (not verified)

@Chaim -
This:
SortedSet set = new SortedSet();
Is not valid, as SortedSet is an interface, not a class. Instead of TreeSet you could use anything that implements SortedSet to initialise the object variable. However you would need to code it yourself or find a different implementation of the SortedSet interface because as far as I'm aware TreeSet is the only implementation that comes with the standard Java libraries.

18 Aug 2010 - 10:53pm by Travis Smith (not verified)

Whoops, I forgot about ConcurrentSkipListSet, which also implements SortedSet.

Post a comment

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image. Ignore spaces and be careful about upper and lower case.