Java Reference
In-Depth Information
The
NavigableMap
Interface
The
TreeMap
class implements the
NavigableMap
interface, which contains methods
similar to the
NavigableSet
interface for navigating and searching a map. Here are some
of the methods in
NavigableMap
:
Map.Entry<K,V> ceilingEntry(K key)
returns a key-value mapping associated with
the least key greater than or equal to the given key.
K ceilingKey(K key)
returns the least key greater than or equal to the given key.
Map.Entry<K,V> floorEntry(K key)
returns a key-value mapping associated with
the greatest key less than or equal to the given key.
K floorKey(K key)
returns the greatest key less than or equal to the given key.
NavigableSet<K> descendingKeySet()
returns a reverse order
NavigableSet
view
of the keys contained in this map.
NavigableMap<K,V> descendingMap()
returns a reverse order view of the mappings
contained in this map.
NavigableMap<K,V> subMap(K fromKey, boolean fromInclusive, K toKey,
boolean toInclusive)
returns a view of the portion of this map whose keys range
from
fromKey
to
toKey
.
The interface also defi nes
headMap
and
tailMap
methods for obtaining subsets at the
beginning and end of the map. Let's look at an example. The following
TreeMap
contains
26 character and integer pairs:
TreeMap<Character, Integer> ascii = new TreeMap<Character, Integer>();
int value = 97;
for(char c = 'a'; c <= 'z'; c++) {
ascii.put(c, value++);
}
Study the following code and see if you can determine its result:
12. Map.Entry<Character, Integer> ceiling = ascii.ceilingEntry('h');
13. System.out.println(“ceiling: “ + ceiling);
14. SortedMap<Character, Integer> tailMap = ascii.tailMap('t');
15. Set<Character> tailKeys = tailMap.keySet();
16. for(Character key : tailKeys) {
17. System.out.print(key + “ “);
18. }
19. System.out.println();
20. NavigableSet<Character> keys = ascii.descendingKeySet();
Search WWH ::
Custom Search