headset, tailset and subset : TreeSet « Collections « Java Tutorial

headSet: The fromElement will be in the subset, while the toElement will not: fromElement <= set view < toElement

If you want the toElement to be in the subset, you must pass in the next node of the tree, or a value that is just beyond the element.

If you are using string nodes, you can adding something to the end:

SortedSet headSet = set.headSet(toElement+"\0");

To remove the fromElement in the subset:

SortedSet tailSet = set.tailSet(fromElement+"\0");

To get a set that includes both ends, use:

SortedSet bothEnds = set.subSet(fromElement, toElement+"\0");

Or, for a set that includes neither end, use:

SortedSet neitherEnd = set.subSet(fromElement+"\0", toElement);
import java.util.Arrays;
import java.util.TreeSet;

public class MainClass {
  public static void main(String args[]) throws Exception {

    String elements[] = { "A", "C", "D", "G", "F" };
    TreeSet set = new TreeSet(Arrays.asList(elements));

    System.out.println(set.subSet("C", "F\0"));
    System.out.println(set.subSet("C", "C\0"));
    System.out.println(set.subSet("C", "C"));
[C, D, F, G]
[A, C]
[D, F, G]
[C, D, F]

While displaying elements in an easily sorted manner is nice, if you don't need the behavior, the cost to add elements and search for them is not worth it.

9.22.1.TreeSet Class
9.22.2.Creating a TreeSet
9.22.3.Get Synchronized Set from TreeSet
9.22.4.Copy all elements in TreeSet to an Object Array
9.22.5.Get Head Set from Java TreeSet
9.22.6.Get lowest and highest value stored in TreeSet
9.22.7.Get Size of TreeSet
9.22.8.Get Sub Set from TreeSet
9.22.9.Get Tail Set from TreeSet
9.22.10.Iterate through elements of TreeSet
9.22.11.Check if a particular value exists in TreeSet
9.22.12.Remove specified element from TreeSet
9.22.13.Remove all elements from TreeSet
9.22.14.The second two constructors are copy constructors
9.22.15.Sort items in a Set
9.22.16.To add a single element: the add() method: public boolean add(Object element)
9.22.17.Retrieving the Ends for a TreeSet
9.22.18.Fetching Elements: the iterator() method: public Iterator iterator()
9.22.19.Working with Subsets
9.22.20.The third method subSet() provides the end points: public SortedSet subSet(Object fromElement, Object toElement)
9.22.21.headset, tailset and subset
9.22.22.Viewing Subsets
9.22.23.Looping through a sorted set backwards