How to Use Lists in Groovy

  • google plus

In Brief...

Lists are quite helpful in Groovy because they give the developer a convenient data structure to store data and to process the data. You can add an item to a list, remove an item from a list and display any item individually. In this topic, we'll consider a list of cities where warehouses for a hypothetical company are located.

Instructions

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

  1. Open your text editor and type in the following lines of Groovy code:
    
    // Use lists in Groovy
    def warehouseCities = ["Orlando", "Las Vegas", "Pittsburgh", "Atlanta"]
    
    println "${warehouseCities.get(0)}"
    warehouseCities.add("Los Angeles")
    
    println "Here are the cities in the list:"
    for (String city : warehouseCities) {
    	print "$city  "
    }
    println " "  // provide a line break after last city
    println "Here are the cities in the list sorted:"
    for (String city : warehouseCities.sort()) {
    	print "$city  "
    }
    println " "  // provide a line break after last city
    def cityRemoved = warehouseCities.get(2)
    warehouseCities.remove(2)
    println "Here are the cities in the list after $cityRemoved removed:"
    for (String city : warehouseCities) {
    	print "$city  "
    }	
    The list is named warehouseCities and is initialized with 4 cities. The first city in the list is then printed. Note that the list index is relative to 0, i.e., 0 references the first element on the list. Next, the list is printed three times. First, in the order in which it was initially stored followed by the cities in ascending order using the sort function. Finally, the list is printed after element "2" (the third item on the list) is removed.
  2. Save your file as UseLists.groovy.
  3. In the command prompt, type in the command to interpret and run your script:
    Run list script
    The output displays the warehouse cities in the list at various stages of processing as explained above.

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