Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 38 ยท Collections and Closures

Ranges and Sets in Groovy

Learn Groovy ranges (inclusive, exclusive, reverse, character, step) and sets (literals, uniqueness, union, intersection, difference, TreeSet, immutability) with examples.

Two small collection types complete your Groovy toolkit: the range, a compact way to say "everything from here to there", and the set, a collection that never holds duplicates. Ranges drive loops, slicing and switch cases. Sets answer questions like "which items are unique?" and "what do these two groups have in common?"

Groovy blocks are read-only; Java stand-ins are runnable.

Ranges

A range is written with two dots. It is a real object that implements List, so every list method works on it:

GROOVY
def r = 1..5
println r                  // [1, 2, 3, 4, 5]
println r.size()           // 5
println r.from             // 1
println r.to               // 5
println r.sum()            // 15
println r.contains(3)      // true
println 7 in r             // false
println r.class            // class groovy.lang.IntRange

Exclusive ranges

Use ..< to leave out the end:

GROOVY
println (1..<5)            // [1, 2, 3, 4]
def list = ['x', 'y', 'z']
println (0..<list.size())  // [0, 1, 2]: the indexes of a list

Half-open ranges match how most programmers count from zero, so for (i in 0..<n) is the Groovy way to write a classic loop.

Reverse and stepped ranges

GROOVY
println (5..1)                    // [5, 4, 3, 2, 1]
println((1..10).step(3))           // [1, 4, 7, 10]
1.step(10, 4) { print "$it " }    // 1 5 9

Character and other ranges

Any type that can be compared and has next() and previous() methods forms a range:

GROOVY
println ('a'..'e')                // [a, b, c, d, e]
println ('a'..'e').collect { it.toUpperCase() }
def today = new Date()
println((today..today + 3).size())       // 4 (dates form a range too)

Ranges are lazy. (1..1_000_000) does not create a million-element list until you ask for the elements, so each over a huge range uses constant memory.

Where ranges are used

GROOVY
def text = 'Groovy'
println text[0..2]                // Gro
println text[-3..-1]              // ovy (counts from the end)
println(['a', 'b', 'c', 'd'][1..2])   // [b, c]
(1..3).each { println it }
def age = 15
switch (age) { case 13..19: println 'teen' }
println((1..10).findAll { it % 2 == 0 })    // [2, 4, 6, 8, 10]

The negative range slice text[-3..-1] selects the last three characters (ovy). A reverse range reverses the slice: text[2..0] gives orG.

The Java stand-in below shows what Groovy's 0..<n and stepping look like with streams.

Java Java stand-in: ranges with IntStream

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Sets

A Set holds each value at most once. Groovy has no special literal for sets; you convert a list with as Set or create a typed one:

GROOVY
def s = [3, 1, 2, 3, 1] as Set
println s                  // [3, 1, 2]  (a LinkedHashSet keeps first-seen order)
println s.class            // class java.util.LinkedHashSet
Set<String> names = ['ada', 'bob'] as Set
def hs = new HashSet([1, 2])
def sorted = [5, 3, 9] as SortedSet      // a TreeSet, sorted
println sorted                           // [3, 5, 9]

Because as Set creates a LinkedHashSet, the insertion order is preserved. A TreeSet keeps its elements sorted by natural order or a comparator.

Working with a set

GROOVY
def tags = [] as Set
tags << 'groovy'
tags << 'java'
tags << 'groovy'           // ignored: already present
println tags.size()        // 2
println 'java' in tags     // true
tags.remove('java')
println tags               // [groovy]

Set operations

GROOVY
def a = [1, 2, 3, 4] as Set
def b = [3, 4, 5] as Set

println a + b              // [1, 2, 3, 4, 5]    union
println a.intersect(b)     // [3, 4]             intersection
println a - b              // [1, 2]             difference
println a.disjoint(b)      // false              share elements?
println b.containsAll([3, 4])   // true          subset check
println (a + b) - a.intersect(b)   // symmetric difference: [1, 2, 5]

+, - and intersect return new sets (when the receiver is a set), so the originals stay unchanged.

Java Java stand-in: union, intersection, difference

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Removing duplicates

The classic use of a set is de-duplication. Both of these keep first-seen order:

GROOVY
def raw = ['b', 'a', 'b', 'c', 'a']
println raw.unique(false)        // [b, a, c]  (copy)
println (raw as Set).toList()    // [b, a, c]

unique also accepts a closure: people.unique { it.email } keeps the first person for each email.

Immutable sets and thread safety

GROOVY
def fixed = ([1, 2] as Set).asImmutable()
// fixed << 3        // UnsupportedOperationException
def shared = Collections.synchronizedSet([] as Set)

Choosing a collection

flowchart TD
    Q["Need to store several values"] --> O{"Do you need keys?"}
    O -->|yes| M["Map"]
    O -->|no| D{"Duplicates allowed?"}
    D -->|yes| L["List"]
    D -->|no| S["Set"]
    L --> R{"Just a run of numbers or letters?"}
    R -->|yes| RG["Range"]

A quick guide: maps for lookups, lists for ordered data with duplicates, sets for uniqueness, ranges for sequences.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does (1..<4) contain?

    ..< excludes the upper bound, so the range is 1, 2, 3.
  2. 2. What does 'Groovy'[-3..-1] return?

    -1 is the last character, so -3..-1 selects the final three characters: o, v, y.
  3. 3. What is [3, 1, 3, 2] as Set in terms of size?

    Duplicates are dropped, leaving 3, 1 and 2.
  4. 4. Which expression gives the elements common to two sets a and b?

    intersect returns the shared elements. disjoint only returns a boolean.
  5. 5. Why is (1..1_000_000).each { } cheap in memory?

    A range stores only its bounds and iterates on demand.

Summary

  • a..b is inclusive, a..<b excludes the end; ranges can run backward, step, and cover characters and dates.
  • Ranges slice lists and strings and appear in switch cases.
  • Sets drop duplicates; as Set keeps insertion order, SortedSet sorts.
  • Use +, -, intersect, disjoint for set algebra.

Next: Closures