Groovy provides range operator (..) to create ranges of object.
Example
Range of integers
src/Example1Range.groovydef numbers = 1..5
println numbers
println numbers.getClass()
for(def n: numbers){
println n;
} Output1..5 class groovy.lang.IntRange 1 2 3 4 5
Reverse range
src/Example2ReverseRange.groovydef numbers = 5..1
for(def n: numbers){
println n;
} Output5 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.groovydef alphas = 'a'..'d'
println alphas.getClass()
for (def a : alphas) {
println a
} Outputclass groovy.lang.ObjectRange a b c d
DateTime ranges:
src/Example4DateTime.groovyimport 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
} OutputJANUARY 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.groovyclass 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
} OutputEvenNumber{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.groovydef numbers = 1..<5
for (def n : numbers) {
println n;
}
Output1 2 3 4
Passing variables
We can also pass variables to the range operator
src/Example7Variable.groovydef x = 5
def y = 10
def numbers = x..<y
for (def n : numbers) {
println n;
} Output5 6 7 8 9
Example ProjectDependencies and Technologies Used: |