|
SortedMap
If you have a SortedMap (of which TreeMap is the only one available), the keys are guaranteed to be in sorted order, which allows additional functionality to be provided with these methods in the SortedMap interface:
Comparator comparator( ): Produces the comparator used for this Map, or null for natural ordering.
Object firstKey( ): Produces the lowest key.
Object lastKey( ): Produces the highest key.
SortedMap subMap(fromKey, toKey): Produces a view of this Map with keys from fromKey, inclusive, to toKey, exclusive.
SortedMap headMap(toKey): Produces a view of this Map with keys less than toKey.
SortedMap tailMap(fromKey): Produces a view of this Map with keys greater than or equal to fromKey.
Here’s an example that’s similar to SortedSetDemo.java and shows this additional behavior of TreeMaps:
//: c11:SimplePairGenerator.java
import com.bruceeckel.util.*;
//import java.util.*;
public class SimplePairGenerator implements MapGenerator {
public Pair[] items = {
new Pair("one", "A"), new Pair("two", "B"),
new Pair("three", "C"), new Pair("four", "D"),
new Pair("five", "E"), new Pair("six", "F"),
new Pair("seven", "G"), new Pair("eight", "H"),
new Pair("nine", "I"), new Pair("ten", "J")
};
private int index = -1;
public Pair next() {
index = (index + 1) % items.length;
return items[index];
}
public static SimplePairGenerator gen =
new SimplePairGenerator();
} ///:~
//: c11:SortedMapDemo.java
// What you can do with a TreeMap.
import com.bruceeckel.simpletest.*;
import com.bruceeckel.util.*;
import java.util.*;
public class SortedMapDemo {
private static Test monitor = new Test();
public static void main(String[] args) {
TreeMap sortedMap = new TreeMap();
Collections2.fill(
sortedMap, SimplePairGenerator.gen, 10);
System.out.println(sortedMap);
Object
low = sortedMap.firstKey(),
high = sortedMap.lastKey();
System.out.println(low);
System.out.println(high);
Iterator it = sortedMap.keySet().iterator();
for(int i = 0; i <= 6; i++) {
if(i == 3) low = it.next();
if(i == 6) high = it.next();
else it.next();
}
System.out.println(low);
System.out.println(high);
System.out.println(sortedMap.subMap(low, high));
System.out.println(sortedMap.headMap(high));
System.out.println(sortedMap.tailMap(low));
monitor.expect(new String[] {
"{eight=H, five=E, four=D, nine=I, one=A, seven=G," +
" six=F, ten=J, three=C, two=B}",
"eight",
"two",
"nine",
"ten",
"{nine=I, one=A, seven=G, six=F}",
"{eight=H, five=E, four=D, nine=I, " +
"one=A, seven=G, six=F}",
"{nine=I, one=A, seven=G, six=F, " +
"ten=J, three=C, two=B}"
});
}
} ///:~
Here, the pairs are stored by key-sorted order. Because there is a sense of order in the TreeMap, the concept of “location” makes sense, so you can have first and last elements and submaps.
|
|