Learn Java for Web Development

(Tina Meador) #1
APPENDIX B: Introduction to Groovy 413

Listing B-20. Creating and Using Ranges



  1. def numRange = 0..9

  2. numRange.each {print it}

  3. println ""

  4. println numRange.contains(5)

  5. def reverseRange = 9..0

  6. reverseRange.each {print it}

  7. def exclusiveRange = 1..<10

  8. println ""

  9. exclusiveRange.each {print it}

  10. def alphabet = 'a'..'z'

  11. println ""

  12. println alphabet.size()

  13. println alphabet[25]


   Lines 1, 5, 7, and 10 illustrate how to define ranges.
 Line 1 defines an inclusive range of numbers.
 Line 10 defines an inclusive range of lowercase letters.
 Line 7 defines an exclusive list of numbers. The range results in a range of
numbers 1 to 9, excluding 10.
 Line 5 creates a range in reverse order, 9 through 0. Frequently, ranges are used for
iterating. In Listing B-20, each() was used to iterate over the range. Listing B-21
shows three ways you can use a range to iterate: one in Java and two in Groovy.

0123456789


true


9876543210


123456789


26


z


Listing B-21. Iterating with Ranges


for (i in 0..9) {
println i
}
(0..9).each { i->
println i
}


The each() method is used to iterate through and apply the closure on every element.

Free download pdf