Wednesday, March 25, 2009

Groovy Ranges

Groovy Collections offer us a class in addition to Java Collections, called Range. Range is a subclass of java.util.List and is used for creating lists of sequential values. Some ranges can be:
Notice that we use the .. operator to create a range.

However ranges are not limited to numbers and characters. Any object which implements the methods compareTo(), next(), and previous() can be used in a Range.

Ranges typically have a left and right border, and they can be either inclusive (containing border elements) or exclusive (sans the right border element).

Ranges are usually used to extract a subset of elements from a list or used in switch statements to match a range of cases together.

The code below is self explanatory:

//A simple Groovy Range
def inclusiveRange = 1..10
println 'The size of inclusiveRange is: ' + inclusiveRange.size()

//This range does not include the right border element
def exclusiveRange = 1..<10 exclusiverange1 =" 1<..10" negativepositiverange =" -5..5" negativedescrange =" -1..-10" negativeascrange =" -10..-1" out =" new" out =" new" out =" new" out =" new" out =" new" list =" [0,1,2,3,4,5,6,7,8,9]"> 0}

Output from running the above program:

The size of inclusiveRange is: 10
inclusiveRange: 1,2,3,4,5,6,7,8,9,10,
exclusiveRange: 1,2,3,4,5,6,7,8,9,
negativePositiveRange: -5,-4,-3,-2,-1,0,1,2,3,4,5,
negativeDescRange: -1,-2,-3,-4,-5,-6,-7,-8,-9,-10,
negativeAscRange: -10,-9,-8,-7,-6,-5,-4,-3,-2,-1,
sublist of first 4 element from list: [0, 1, 2, 3]
sublist of last 2 element from list: [9, 8]
negativeAscRange,grep(-5..-3): [-5, -4, -3]
matching all positive values in negativePositiveRange: [1, 2, 3, 4, 5]

No comments: