Course contentsShow
← Java
Lesson 1140 of 2,87026. Map ImplementationsFree lesson

NavigableMap Operations: headMap, tailMap, subMap

Creating views of TreeMap ranges based on key boundaries with inclusive/exclusive parameters.

NavigableMap Operations: headMap, tailMap, subMap

What you'll learn: How to create focused views of a TreeMap that show only entries within specified key ranges.

The Core Idea

Just as you can view a subset of a NavigableSet, a NavigableMap lets you create views of portions of your map based on key boundaries. These aren't copies—they're live windows into the original map. Think of it like looking at a photo album through a cardboard frame that only reveals certain pages: move the frame, and you see different photos, but the album itself hasn't changed.

The Three Range Methods

headMap(K toKey, boolean inclusive): Returns a view of all entries whose keys are less than (or equal to, if inclusive) toKey.

tailMap(K fromKey, boolean inclusive): Returns a view of all entries whose keys are greater than (or equal to, if inclusive) fromKey.

subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive): Returns a view of entries between fromKey and toKey, with separate control over including each boundary.

Understanding Inclusive vs Exclusive

The boolean parameters control whether boundary keys themselves appear in the view:

  • true (inclusive) means "include this exact key if it exists"
  • false (exclusive) means "stop just before this key"

For example, headMap("M", false) gives you all entries before "M", but not "M" itself. tailMap("M", true) includes "M" and everything after.

Why This Matters

These views let you work with logical subsets of your map without duplicating data. Changes to the view affect the original TreeMap, and vice versa. You can iterate over just the entries you care about, making range-based operations efficient.

Key Takeaway: TreeMap's headMap, tailMap, and subMap create live, range-based views controlled by key boundaries and inclusive/exclusive parameters, letting you work with map subsets without copying data.