0Pricing
Java Academy · Lesson

Submaps and Range Views

Extract subMap, headMap, and tailMap views for range-based lookups in sorted maps.

Range Views in TreeMap

TreeMap's subMap, headMap, and tailMap return backed views — they reflect changes in the underlying map and vice versa. Changes through the view are reflected in the original.

TreeMap<Integer, String> map = new TreeMap<>();
for (int i = 1; i <= 10; i++) map.put(i * 10, "item" + i);

var view = map.subMap(30, 70); // [30, 70)
System.out.println(view); // {30=item3, 40=item4, 50=item5, 60=item6}

map.put(45, "new"); // also visible through view!
System.out.println(view.containsKey(45)); // true

headMap: Keys Below a Bound

headMap(toKey) returns all entries with keys strictly less than toKey. Use the inclusive variant headMap(toKey, true) to include the bound.

TreeMap<String, Integer> words = new TreeMap<>();
"banana cherry apple date elderberry".chars()
    .mapToObj(c -> String.valueOf((char)c)).distinct()
    .forEach(w -> words.put(w, w.length()));
// Actually let's use real words:
TreeMap<String, Integer> wc = new TreeMap<>();
wc.put("apple",5); wc.put("banana",6); wc.put("cherry",6); wc.put("date",4);

System.out.println(wc.headMap("cherry")); // {apple=5, banana=6}

All lessons in this course

  1. TreeMap: Sorted Key-Value Pairs
  2. Submaps and Range Views
  3. TreeSet and NavigableSet
  4. Custom Ordering in Tree Collections
← Back to Java Academy