Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Mail Systems
Eclipse Documentation

How To Guides
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Problem Solutions




Thinking in Java
Prev Contents / Index Next


If you have a SortedSet (of which TreeSet is the only one available), the elements are guaranteed to be in sorted order, which allows additional functionality to be provided with these methods in the SortedSet interface:

Comparator comparator( ): Produces the Comparator used for this Set, or null for natural ordering.

Object first( ): Produces the lowest element.

Object last( ): Produces the highest element.

SortedSet subSet(fromElement, toElement): Produces a view of this Set with elements from fromElement, inclusive, to toElement, exclusive.

SortedSet headSet(toElement): Produces a view of this Set with elements less than toElement.

SortedSet tailSet(fromElement): Produces a view of this Set with elements greater than or equal to fromElement.

Here’s a simple demonstration:

// What you can do with a TreeSet.
import com.bruceeckel.simpletest.*;
import java.util.*;

public class SortedSetDemo {
  private static Test monitor = new Test();
  public static void main(String[] args) {
    SortedSet sortedSet = new TreeSet(Arrays.asList(
    "one two three four five six seven eight".split(" ")));
      low = sortedSet.first(),
      high = sortedSet.last();
    Iterator it = sortedSet.iterator();
    for(int i = 0; i <= 6; i++) {
      if(i == 3) low =;
      if(i == 6) high =;
    System.out.println(sortedSet.subSet(low, high));
    monitor.expect(new String[] {
      "[eight, five, four, one, seven, six, three, two]",
      "[one, seven, six, three]",
      "[eight, five, four, one, seven, six, three]",
      "[one, seven, six, three, two]"
} ///:~

Note that SortedSet means “sorted according to the comparison function of the object,” not “insertion order.”

Thinking in Java
Prev Contents / Index Next

   Reproduced courtesy of Bruce Eckel, MindView, Inc. Design by Interspire