Over a million developers have joined DZone.

Groovy Goodness: Using String Values in Ranges [Snippet]

DZone's Guide to

Groovy Goodness: Using String Values in Ranges [Snippet]

Want to see how to use String values in your ranges? Here's a quick lesson to set up inclusive and exclusive ranges in Groovy.

· Java Zone ·
Free Resource

Atomist automates your software deliver experience. It's how modern teams deliver modern software.

We can use ranges in Groovy using an easy syntax where the start and end values of the range are separated by .. for an inclusive range and ..< for an exclusive range as we have seen in a previous post. The values of the range are mostly numbers or enum values. But we can also use String values to define a range. Groovy will check if the String values are the same length and if the values, except for the last character, are the same. Then the natural ordering of the last character of the String value, based on the character's int value, is used to create the range values.

In the following example, we define several ranges using String values. We can even define a reverse range using String values.

// Range is defined based on int
// value of character.
def characters = 'A'..'F'
assert characters.from == 'A'
assert characters.to == 'F'
assert characters.toList() == ['A', 'B', 'C', 'D', 'E', 'F']
assert characters.step(2) == ['A', 'C', 'E']
// We can create a reverse range
// also based on the int value
// of the character.
def sample = '&'..'!'
assert sample.toList() == ['&', '%', '$', '#', '"', '!']
assert sample.reverse
assert sample.from == '!'
assert sample.to == '&'
// We can use String values and
// the last character is used
// to create a range. Therefore
// the last character must be valid
// to create a range from.
def groovyRange = 'Groovy10'..<'Groovy15'
assert groovyRange.from == 'Groovy10'
assert groovyRange.to == 'Groovy14'
assert groovyRange.toList() == ['Groovy10', 'Groovy11', 'Groovy12', 'Groovy13', 'Groovy14']
// Also works in reverse.
def groovyReverse = 'Groovy19'..'Groovy15'
assert groovyReverse.reverse
assert groovyReverse.from == 'Groovy15'
assert groovyReverse.to == 'Groovy19'
assert groovyReverse.toList() == ['Groovy19', 'Groovy18', 'Groovy17', 'Groovy16', 'Groovy15']
import static groovy.test.GroovyAssert.shouldFail
// Should fail because String values,
// except for the last character, should
// be the same.
shouldFail(IllegalArgumentException) {
    def invalidRange = 'Groovy15'..'Groovy20'

Written with Groovy 2.5.0.

Get the open source Atomist Software Delivery Machine and start automating your delivery right there on your own laptop, today!

java ,groovy ,ranges ,string

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}