Fundamentals 10 min read

Master Google Guava's RangeSet to Supercharge Your Code Efficiency

This article explains Guava's RangeSet API, detailing its automatic range merging, logarithmic‑time queries, flexible set operations, underlying range‑tree implementation, and provides a complete Java example that demonstrates creation, manipulation, and iteration of range collections.

Programmer1970
Programmer1970
Programmer1970
Master Google Guava's RangeSet to Supercharge Your Code Efficiency

1. Introduction to RangeSet

RangeSet is an interface in Guava that represents a set of non‑overlapping, non‑empty ranges. Each range is a Range object with lower and upper bounds. The API provides methods such as contains(C), rangeContaining(C), encloses(Range) and span() to query and manipulate the set.

2. Core Features

Automatic merging : Adding a new range merges it with any intersecting or adjacent ranges, preserving the non‑overlapping invariant.

Efficient queries : Membership tests and range look‑ups run in logarithmic time by traversing the underlying range tree.

Flexible operations : Supports union, intersection, difference and complement operations, enabling complex range manipulations.

3. Implementation Details

Guava implements RangeSet with a balanced “range tree”. Nodes store ranges sorted by their lower endpoint. Insertion walks the tree to locate overlapping or adjacent ranges, merges them, and re‑balances the tree. Both insertion and query have O(log n) complexity.

4. Practical Usage

Before using RangeSet, understand the Range type, which expresses intervals such as Range.closed(1, 3) or Range.open(5, 8). The following example demonstrates creation, addition, removal, containment checks, complement, sub‑range extraction and iteration.

Range class diagram
Range class diagram
import com.google.common.collect.Range;
import com.google.common.collect.RangeSet;
import com.google.common.collect.TreeRangeSet;

public class TreeRangeSetDemo {
    public static void main(String[] args) {
        // Create an empty TreeRangeSet
        RangeSet<Integer> rangeSet = TreeRangeSet.create();

        // Add disjoint ranges
        rangeSet.add(Range.closed(1, 3));      // [1, 3]
        rangeSet.add(Range.open(5, 8));        // (5, 8)
        rangeSet.add(Range.closedOpen(10,12)); // [10, 12)
        rangeSet.add(Range.greaterThan(15));   // (15, +∞)

        System.out.println(rangeSet); // [1..3](5..8)[10..12)(15..+∞)

        // Containment checks
        System.out.println(rangeSet.contains(Range.closed(2,3))); // true
        System.out.println(rangeSet.contains(Range.open(6,7)));   // true
        System.out.println(rangeSet.contains(Range.closed(4,5))); // false

        // Remove a range
        rangeSet.remove(Range.open(5,8));
        System.out.println(rangeSet); // [1..3][10..12)(15..+∞)

        // Sub‑range set overlapping a given range
        RangeSet<Integer> overlapping = rangeSet.subRangeSet(Range.atLeast(9));
        System.out.println(overlapping); // [10..12)(15..+∞)

        // Complement within [0,20]
        RangeSet<Integer> complement = rangeSet.complement()
                .subRangeSet(Range.closed(0,20));
        System.out.println(complement); // (0..1)(3..5)(8..10)[12..15][15..20]

        // Encloses examples
        System.out.println(rangeSet.encloses(Range.closed(2,3))); // true
        System.out.println(rangeSet.encloses(Range.open(6,7)));   // true
        System.out.println(rangeSet.encloses(Range.singleton(11))); // true
        System.out.println(rangeSet.encloses(Range.closed(4,5))); // false

        // Iterate over ranges
        for (Range<Integer> r : rangeSet.asRanges()) {
            System.out.println(r);
        }
    }
}

The demo shows how RangeSet automatically merges adjacent intervals, provides logarithmic‑time queries, and supports complement, sub‑range extraction and iteration.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaData StructuresGoogle GuavaRangeSetrange operationsTreeRangeSet
Programmer1970
Written by

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.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.