Maps: TreeMap subMap, headMap and tailMap are live views

A NavigableMap can be sliced by key range. The slices are views, so writes through them are visible in the original map.

Code
NavigableMap<Integer, String> byId = new TreeMap<>();
for (int i = 10; i <= 50; i += 10) byId.put(i, "item" + i);

System.out.println("full     : " + byId);
System.out.println("headMap(30)          : " + byId.headMap(30));
System.out.println("tailMap(30)          : " + byId.tailMap(30));
System.out.println("subMap(20, true, 40, true): " + byId.subMap(20, true, 40, true));
System.out.println("descendingMap        : " + byId.descendingMap());
Output
full     : {10=item10, 20=item20, 30=item30, 40=item40, 50=item50}
headMap(30)          : {10=item10, 20=item20}
tailMap(30)          : {30=item30, 40=item40, 50=item50}
subMap(20, true, 40, true): {20=item20, 30=item30, 40=item40}
descendingMap        : {50=item50, 40=item40, 30=item30, 20=item20, 10=item10}
Advertisement

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-07-30