Get the head set and tail set

SortedSet<E> headSet(E toElement)
Returns a view of the portion of this set whose elements are strictly less than toElement.
NavigableSet<E> headSet(E toElement, boolean inclusive)
Returns a view of the portion of this set whose elements are less than (or equal to, if inclusive is true) toElement.
SortedSet<E> tailSet(E fromElement)
Returns a view of the portion of this set whose elements are greater than or equal to fromElement.
NavigableSet<E>
tailSet(E fromElement, boolean inclusive) Returns a view of the portion of this set whose elements are greater than (or equal to, if inclusive is true) fromElement.

  import java.util.Arrays;
import java.util.TreeSet;

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

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

    System.out.println(set.headSet("D"));
    System.out.println(set.tailSet("D"));
  }
}
  

The output:


[C]
[D, F, G, java2s.com]
Home 
  Java Book 
    Collection  

TreeSet:
  1. TreeSet class
  2. Create TreeSet objects
  3. Add elements to a TreeSet
  4. Get the least and greatest element in this TreeSet'>
  5. The first and last element in this TreeSet
  6. Get the head set and tail set
  7. Remove element from TreeSet
  8. Get the size of this TreeSet
  9. Get a subset from this TreeSet