Sets and ranges
A set holds each value once, and a range writes a sequence without listing it. Both are collections, so the GDK methods of the next lesson work on them.
A set without duplicates
sets.groovy
def raw = ['groovy', 'jvm', 'groovy', 'script']
def tags = raw as Set
tags << 'gradle'
println tags
println tags.sort()
println tags.size()
println tags.contains('script')
println tags + (['dsl'] as Set)
println tags.intersect(['groovy', 'java'] as Set)
groovy sets.groovy
[groovy, jvm, script, gradle]
[gradle, groovy, jvm, script]
4
true
[groovy, jvm, script, gradle, dsl]
[groovy]
as Set converts a list and drops the duplicates, and the object is a LinkedHashSet: the order of the first occurrence stays. + is the union and intersect the intersection, both returning a new set.
Ranges
ranges.groovy
println(1..5)
println(1..<5)
println('a'..'e')
println((1..10).step(3))
println((1..5).sum())
println((1..5).collect { it * it })
println(5 in 1..10)
groovy ranges.groovy
1..5
1..<5
a..e
[1, 4, 7, 10]
15
[1, 4, 9, 16, 25]
true
.. includes the last value and ..< excludes it. A range of characters works because a String is comparable, and step walks every n-th element without building the list.
A range as a loop and as an index
index.groovy
def letters = ['a', 'b', 'c', 'd', 'e']
for (int index in 0..<letters.size()) {
println "${index}: ${letters[index]}"
}
println letters[1..3]
println letters[-2..-1]
groovy index.groovy
0: a
1: b
2: c
3: d
4: e
[b, c, d]
[d, e]
0..<size() is the safe index range: it stops before the size, which is the one off-by-one a range removes. A negative range counts from the end.
Related
- Spread, subscript and generics: typed collections and the spread operator.
- Loops: the range in a loop.
Article author: Arthur Isaev