A NavigableMap exposes ordered boundary lookups and range views whose contents can remain connected to the backing map.
Java NavigableMap ranges: distinguish a live window from a snapshot
This complete program targets Java 8. Its displayed output is checked by the tutorial validation script.
A view is still the same data owner
A dispatch ledger stores timestamps ten, twenty and thirty. The half-open window from ten to thirty excludes the record at thirty. Replacing twenty through that window replaces it in the original ledger as well. A TreeMap copy captures the selected entries at that moment and does not observe a later insert.
The fixture also asks floorEntry for twenty-four and receives the entry at twenty. That is a predecessor lookup, not exact equality. Pick floor, ceiling, lower or higher from the boundary rule instead of adding ad hoc off-by-one arithmetic to an exact-key lookup.
The window rejects outside writes
Inserting forty into the selected window raises IllegalArgumentException. That is a range restriction on the view, not proof of a domain-level permission check. A different reference to the backing map can still write forty.
Copying the map copies entry references rather than making mutable values independent. Here strings make the snapshot distinction straightforward; a mutable dispatch record needs a separate copy policy. View ownership and Response snapshots explain why returning a view can expose more ownership than intended.
Working program
import java.util.*;
public class DispatchRangeWindow {
public static void main(String[] args) {
NavigableMap<Integer,String> ledger=new TreeMap<>();
ledger.put(10,"queued");ledger.put(20,"review");ledger.put(30,"sent");
NavigableMap<Integer,String> window=ledger.subMap(10,true,30,false);
NavigableMap<Integer,String> snapshot=new TreeMap<>(window);
window.put(20,"approved");ledger.put(25,"packed");
System.out.println(window);System.out.println(snapshot);System.out.println(ledger.floorEntry(24).getKey());
try{window.put(40,"outside");}catch(IllegalArgumentException rejected){System.out.println("range rejected");}
}
}Output
{10=queued, 20=approved, 25=packed}
{10=queued, 20=review}
20
range rejectedCosts and boundaries
TreeMap predecessor lookup and insertion take O(log n) time. A live range view does not copy all matching entries, while building a snapshot retains O(k) entry data for k selected entries. Iterating the range still visits the entries requested.
Common Mistakes
- State whether each endpoint is inclusive.
- Do not describe a live view as an independent snapshot.
- A range restriction is not an authorization policy.
Read next
Java TreeMap: ordered keys and range views, Java collection views: live wrappers, snapshots and shallow copies, Spring API pagination: bounded requests and immutable snapshots.
