Navigating (Searching) TreeSets and TreeMaps : TreeSet « Utility Classes « SCJP






import java.util.TreeSet;

public class MainClass {
  public static void main(String[] args) {
    TreeSet<Integer> times = new TreeSet<Integer>();
    times.add(1205);
    times.add(1505);
    times.add(1545);
    times.add(1830);
    times.add(2010);
    times.add(2100);
    // Java 5 version

    TreeSet<Integer> subset = new TreeSet<Integer>();
    subset = (TreeSet) times.headSet(1600);
    System.out.println("last before 4pm is: " + subset.last());

    TreeSet<Integer> sub2 = new TreeSet<Integer>();
    sub2 = (TreeSet) times.tailSet(2000);
    System.out.println("first after 8pm is: " + sub2.first());

    // Java 6 version using the new lower() and higher() methods

    System.out.println("last before 4pm is: " + times.lower(1600));
    System.out.println("first after 8pm is: " + times.higher(2000));
  }
}

last before 4pm is: 1545
first after 8pm is: 2010
last before 4pm is: 1545
first after 8pm is: 2010




Important "Navigation" Related Methods

Method                           Description

TreeSet.ceiling(e)               Returns the lowest element >= e

TreeMap.ceilingKey(key)          Returns the lowest key >= key

TreeSet.higher(e)                Returns the lowest element > e

TreeMap.higherKey(key)           Returns the lowest key > key

TreeSet.floor(e)                 Returns the highest element <= e

TreeMap.floorKey(key)            Returns the highest key <= key

TreeSet.lower(e)                 Returns the highest element < e

TreeMap.lowerKey(key)            Returns the highest key < key

TreeSet.pollFirst()              Returns and removes the first entry

TreeMap.pollFirstEntry()         Returns and removes the first key-value pair

TreeSet.pollLast()               Returns and removes the last entry

TreeMap.pollLastEntry()          Returns and removes the last key-value pair

TreeSet.descendingSet()          Returns a NavigableSet in reverse order

TreeMap.descendingMap()          Returns a NavigableMap in reverse order








8.17.TreeSet
8.17.1.An Iterator from TreeSet presents elements in some kind of sorted order.
8.17.2.The TreeSet class implements the java.util.SortedSet interface, which extends java.util.Set.
8.17.3.Use TreeSet to sort random numbers
8.17.4.Navigating (Searching) TreeSets and TreeMaps