Java Reference
In-Depth Information
SortedMap<K, V> headMap(K toKey)
: It returns a view of the
SortedMap
whose entries will
have keys less than the specified
toKey
. If you add a new entry to the view, its key must be
less than the specified
toKey
. Otherwise, it will throw an exception. The view is backed by the
original
SortedMap
.
•
•
K lastKey()
: It returns the key of the last entry in the
SortedMap
. If the
SortedMap
is empty, it
throws a
NoSuchElementException
.
•
SortedMap<K, V> subMap(K fromKey, K toKey)
: It returns a view of the
SortedMap
whose
entries will have keys ranging from the specified
fromKey
(inclusive) and
toKey
(exclusive).
The original
SortedMap
backs the partial view of the
SortedMap
. Any changes made to either
map will be reflected in both. You can put new entries in the sub map whose keys must fall in
the range
fromKey
(inclusive) and
toKey
(Exclusive).
SortedMap<K, V> tailMap(K fromKey)
: It returns a view of the
SortedMap
whose entries will
have keys equal to or greater than the specified
fromKey
. If you add a new entry to the view,
its key must be equal to or greater than the specified
fromKey
. Otherwise, it will throw an
exception. The original
SortedMap
backs the tail view.
The
TreeMap
class is the implementation class for the
SortedMap
interface. For basic operations, you work with a
SortedMap
the same way as you work with a
Map
. Listing 12-31 demonstrates how to use a
SortedMap
.
•
Listing 12-31.
Using a SortedMap
// SortedMapTest.java
package com.jdojo.collections;
import java.util.SortedMap;
import java.util.TreeMap;
public class SortedMapTest {
public static void main(String[] args) {
SortedMap<String,String> sMap = new TreeMap<>();
sMap.put("John", "(342)113-9878");
sMap.put("Richard", "(245)890-9045");
sMap.put("Donna","(205)678-9823");
sMap.put("Ken", "(205)678-9823");
System.out.println("Sorted Map: " + sMap);
// Get a sub map from Donna (inclusive) to Ken(exclusive)
SortedMap<String,String> subMap = sMap.subMap("Donna", "Ken");
System.out.println("Sorted Submap from Donna to Ken(exclusive): " + subMap);
// Get the first and last keys
String firstKey = sMap.firstKey();
String lastKey = sMap.lastKey();
System.out.println("First Key: " + firstKey);
System.out.println("Last key: " + lastKey);
}
}