How to Use Ranges in Groovy

  • google plus

In Brief...

Ranges in Groovy are lists containing sequential values. A range is of type Range (from Java) and extends java.util.List. As an example, consider a demographic range for a target radio audience for ages 18 to 30. The values stored in this list would be 18,19, 20 and so on up to and including 30. We will explore this scenario in the example below.

Instructions

To learn how to use ranges in Groovy follow these 3 steps:

  1. Open your text editor and type in the following lines of Groovy code:
    
    def targetAudienceAges = 18..30
    def sampleAge=27
    println "$targetAudienceAges"
    println "First age in range: ${targetAudienceAges.from}"
    println "Last age in range: ${targetAudienceAges.to}"
    if (sampleAge ≥ targetAudienceAges.from && sampleAge < targetAudienceAges.to) {
    	println "Sample age is within target audience range"
    }
    else {
    	println "Sample age is not within target audience range"
    }	
    println "Here are the ages in the list:"
    for (int age : targetAudienceAges) {
    	print "$age "
    }
    
    The name of the range is tragetAudienceAges and contains the integers 18 up to 30. Note the from property that gives us access to the first number in the range. The to property references the last number in the range. We can verify a given integer, e.g., sampleAge, is present in the range by applying and if statement as shown in the source code. The program then prints out each age in the list.
  2. Save your file as Use.groovy.
  3. In the command prompt, type in the command to interpret and run your script:
    Run range script
    The output displays the integers in the list as well as the beginning and ending integers. The output verifies that the sample age is present in the range. Then the individual ages in the range are printed.

Author: Stephen Withrow

Stephen has over 30 years' experience in training, development, and consulting in a variety of technology areas including Java, C, C++, XML, JavaScript, AJAX, Tomcat, JBoss, Oracle, and DB2. His background includes design and implementation of business solutions on client/server, Web, and enterprise platforms. Stephen is a published writer in both technical and non-technical endeavors. Stephen received an undergraduate degree in Computer Science and Physics from Florida State University.

Discuss