TreeMap sub map
In this chapter you will learn:
Submap a TreeMap
TreeMap
are ordered by key's value. We can
think the key value in a TreeMap
as a
list. In that way we can get a sub list for a range of values.
SortedMap<K,V> subMap(K fromKey, K toKey)
Returns the portion of this map whose keys range from fromKey, inclusive, to toKey, exclusive.
import java.util.TreeMap;
/* j a v a 2s.c o m*/
public class Main {
public static void main(String[] args) {
TreeMap<Integer, String> db = new TreeMap<Integer, String>();
db.put(1000, "1000");
db.put(1011, "1011");
db.put(1102, "1102");
db.put(2023, "2023");
db.put(2034, "2034");
System.out.println(db.subMap(1000, 1999) + "\n");
System.out.println(db.tailMap(1011) + "\n");
System.out.println(db.headMap(2023));
System.out.println("First key higher than 2034: " + db.higherKey(2034));
System.out.println("First key lower than 2034: " + db.lowerKey(2034));
}
}
The code above generates the following result.
Next chapter...
What you will learn in the next chapter:
Home » Java Tutorial » Collections