Close

Groovy Operators - Range Operator

[Last Updated: Dec 18, 2018]

Groovy provides range operator (..) to create ranges of object.

Example

Range of integers

src/Example1Range.groovy

def numbers = 1..5
println numbers
println numbers.getClass()
for(def n: numbers){
    println n;
}

Output

1..5
class groovy.lang.IntRange
1
2
3
4
5

Reverse range

src/Example2ReverseRange.groovy

def numbers = 5..1
for(def n: numbers){
    println n;
}

Output

5
4
3
2
1

Object Range

Range operator works for all objects which implements Comparable and which provide some means to determine next and previous values.

Range of characters:

src/Example3String.groovy

def alphas = 'a'..'d'
println alphas.getClass()
for (def a : alphas) {
    println a
}

Output

class groovy.lang.ObjectRange
a
b
c
d

DateTime ranges:

src/Example4DateTime.groovy

import java.time.LocalTime
import java.time.Month

def monthRange = Month.JANUARY..Month.APRIL
for (def month : monthRange) {
    println month
}

def timeRange = LocalTime.now()..LocalTime.now().plusSeconds(2)
for (def time : timeRange) {
    println time
}

Output

JANUARY
FEBRUARY
MARCH
APRIL
20:36:28.959379200
20:36:29.959379200
20:36:30.959379200

Creating custom object used with range operator

We can create a range from any Comparable object that has next() and previous() methods to determine the next/previous item in the range.

src/Example5Custom.groovy

class EvenNumber implements Comparable<EvenNumber> {
    private int num;

    EvenNumber(int num) {
        this.num = num;
    }

    public EvenNumber next() {
        return new EvenNumber(num + 2);
    }

    public EvenNumber previous() {
        return new EvenNumber(num - 2);
    }

    @Override
    int compareTo(EvenNumber o) {
        return Integer.compare(num, o.num);
    }

    @Override
    public String toString() {
        return "EvenNumber{" +
                "num=" + num +
                '}';
    }
}

def theRange = new EvenNumber(4)..new EvenNumber(8)
for (def r : theRange) {
    println r
}
//reverse
println '-- reverse --'
theRange = new EvenNumber(8)..new EvenNumber(4)
for (def r : theRange) {
    println r
}

Output

EvenNumber{num=4}
EvenNumber{num=6}
EvenNumber{num=8}
-- reverse --
EvenNumber{num=8}
EvenNumber{num=6}
EvenNumber{num=4}

Exclusivity

To exclude upper bound we can use range operator as a..<b

src/Example6Exclusive.groovy

def numbers = 1..<5
for (def n : numbers) {
    println n;
}

Output

1
2
3
4

Passing variables

We can also pass variables to the range operator

src/Example7Variable.groovy

def x = 5
def y = 10
def numbers = x..<y
for (def n : numbers) {
    println n;
}

Output

5
6
7
8
9

Example Project

Dependencies and Technologies Used:

  • Groovy 2.5.3
  • JDK 9.0.1
Groovy - Range Operator Select All Download
  • groovy-range-operator
    • src
      • Example1Range.groovy

    See Also