Boost Coding Efficiency with Google Guava’s RangeMap: Mastering Interval Mapping
The article explains Google Guava’s RangeMap—a map that links non‑overlapping ranges to values—detailing its core features, typical use cases such as retry mechanisms and tiered pricing, and provides step‑by‑step Java code examples that show insertion, querying, overlapping handling, sub‑range views, and removal.
1. Introduction to RangeMap
RangeMap is a special map in Guava that maps non‑overlapping, non‑empty Ranges to specific values. Unlike a traditional Map, the key is a range rather than a single element, making it useful for behavior that depends on intervals.
2. Application Scenarios
Retry mechanism: Map time intervals to different retry strategies.
Tiered pricing: Map usage or amount ranges to corresponding fees.
Configuration management: Map configuration ranges to behaviors.
3. Core Features
No automatic merging of adjacent ranges: Even if adjacent ranges map to the same value, they remain separate.
Red‑black‑tree implementation: TreeRangeMap uses a red‑black tree for efficient look‑up and insertion.
Flexible range definitions: Supports open, closed, half‑open intervals, etc.
Insertion of overlapping ranges: Overlapping new ranges cause the existing ones to be split, preserving the new range intact.
Split original ranges to keep them non‑overlapping.
Keep the inserted range whole.
Single‑key query: get(K) finds the value whose range contains K using the internal tree.
4. Using RangeMap
Common methods:
Example code:
import com.google.common.collect.Range;
import com.google.common.collect.RangeMap;
import com.google.common.collect.TreeRangeMap;
import java.util.Map;
public class TreeRangeMapExample {
public static void main(String[] args) {
// Create an empty TreeRangeMap
RangeMap<Integer, String> rangeMap = TreeRangeMap.create();
// Add mappings
rangeMap.put(Range.closed(0, 4), "Low");
rangeMap.put(Range.open(5, 10), "Medium");
rangeMap.put(Range.closedOpen(10, 15), "High");
rangeMap.put(Range.greaterThan(15), "Very High");
// Query single keys
System.out.println(rangeMap.get(2)); // Low
System.out.println(rangeMap.get(5)); // null (5 not in any range)
System.out.println(rangeMap.get(7)); // Medium
System.out.println(rangeMap.get(10)); // null (needs get(Range))
System.out.println(rangeMap.get(12)); // High
System.out.println(rangeMap.get(20)); // Very High
// Query by range
System.out.println(rangeMap.get(Range.singleton(10))); // High
// Sub‑range view
RangeMap<Integer, String> subRangeMap = rangeMap.subRangeMap(Range.closedOpen(6, 12));
System.out.println(subRangeMap.asMapOfRanges()); // {(6,10)=Medium, [10,12)=High}
// Full view
System.out.println(rangeMap.asMapOfRanges());
// Remove a range
rangeMap.remove(Range.closed(0, 4));
System.out.println(rangeMap.asMapOfRanges());
// Iterate
for (Map.Entry<Range<Integer>, String> entry : rangeMap.asMapOfRanges().entrySet()) {
System.out.println(entry.getKey() + " => " + entry.getValue());
}
}
}The get method returns the value for the range containing the key or null if none. asMapOfRanges() shows all mappings.
Overlapping range behavior:
// Insert overlapping range [3,8)
rangeMap.put(Range.closedOpen(3, 8), "Overlap");
System.out.println(rangeMap.asMapOfRanges());
// Output: {[0,3]=Low, (3,8)=Overlap, [8,10)=Medium, [10,15)=High, (15,∞)=Very High}
// Span a query range
Range<Integer> queryRange = Range.closedOpen(2, 12);
RangeMap<Integer, String> spanned = rangeMap.span(queryRange);
System.out.println(spanned.asMapOfRanges());
// Output: {(2,3]=Low, [3,8)=Overlap, [8,10)=Medium, [10,12)=High}
// Endpoints
System.out.println("lower endpoint: " + queryRange.lowerEndpoint());
System.out.println("upper endpoint: " + queryRange.upperEndpoint());Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Programmer1970
Formerly called 'Code to 35'. Add our main WeChat ID to access a wealth of shared resources (algorithms, interview prep, tech stacks: Java, Python, Go, big data). We mainly share serious development techniques, focusing on output-driven input. Occasionally we post life snippets and gossip. Our aim is to attract precise traffic and test advertising opportunities.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
