Groovy

Groovy Each Example

1. Introduction

Apache Groovy (Groovy) is an object-oriented dynamic programming language for the Java platform. It is dynamically compiled to the Java Virtual Machine (JVM) bytecode, and inter-operates with other Java source codes and libraries. Groovy is written in Java and was first released in 2007.

Groovy each and eachWithIndex methods are defined in Groovy Object, so we can use them for any object.

In this example, I will demonstrate how to use the Groovy each and eachWithIndex methods for various common object types in a Maven project.

2. Technologies Used

The example code in this article was built and run using:

  • Java 1.8.101 (1.8.x will do fine)
  • Maven 3.3.9 (3.3.x will do fine)
  • Eclipse Mars (Any Java IDE would work)
  • Groovy 2.4

3. Maven Project

In this step, we will build unit test classes to demonstrate the each method for String, int, long, Object, and a collection with various different items. I will also show how to use the eachWithIndex method in a collection.

3.1 Dependencies

We will add Groovy dependency in the pom.xml.

pom.xml

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
    <modelVersion>4.0.0</modelVersion>
    <groupId>jcg-zheng-demo</groupId>
    <version>1.0.0-SNAPSHOT</version>
    <artifactId>groovy-demo</artifactId>
 
    <build>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.3</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
 
    <dependencies>
        <dependency>
            <groupId>org.codehaus.groovy</groupId>
            <artifactId>groovy-all</artifactId>
            <version>2.4.13</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
 
</project>

3.2 Person

We will create a Person class to show the each method on an object.

Person.groovy

1
2
3
4
5
6
7
8
9
package jcg.zheng.demo.groovy
 
import groovy.transform.Canonical
 
@Canonical
class Person {
    String firstName
    String lastName
}

3.3 Each on an Object

public Object each(Closure closure): Iterates through an aggregate type or data structure, passing each item to the given closure. Custom types may utilize this method by simply providing an “iterator()” method. The items returned from the resulting iterator will be passed to the closure.

In this step, we will build unit tests to call the each method for String, number and Object.

EachDemoObject.groovy

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package jcg.zheng.demo.groovy
 
import static org.junit.Assert.*
 
import org.junit.Test
 
class EachDemoObject {
 
    @Test
    public void each_in_string(){
        String str = "Hello World!"
        str.each { println it}
    }
 
    @Test
    public void each_in_number(){
        int num = 100
        num.each { println it}
    }
 
 
    @Test
    public void each_in_object(){
        def person = new Person("Mary", "Zheng")
        person.each { println it}
    }
}

Output of each_in_number for number 100.

Output from each_in_number

1
100

Output from each_in_string for “Hello World!”

Output from each_in_string

01
02
03
04
05
06
07
08
09
10
11
12
H
e
l
l
o
  
W
o
r
l
d
!

Output from each_in_object for a Person.

Output from each_in_object

1
jcg.zheng.demo.groovy.Person(Mary, Zheng)

3.4 Each for a Collection

In this step, we will build unit tests to invoke each method for a collection of list, map, set, and range.

EachDemoCollection.groovy

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package jcg.zheng.demo.groovy
 
import static org.junit.Assert.*
 
import org.junit.Test
 
class EachDemoCollection {
 
    @Test
    public void each_in_collection_array(){
        String[] names = ["Mary", "Becky", "Susan", "Tom"]
        names.each { println it}
    }
 
    @Test
    public void each_in_collection_list(){
        List names = ["Mary", "Becky", "Susan", "Tom"]
        names.each { println it}
    }
 
    @Test
    public void each_in_collection_map(){
        def names  = [:]
        names["id001"]= "Mary"
        names["id002"]= "Alex"
        names["id003"]= "Allen"
        names["id004"]= "Sammo"
        names.each { println it}
    }
 
    @Test
    public void each_in_collection_range(){
        def numbers  = (1..10)
        numbers.each { println it}
    }
 
    @Test
    public void each_in_collection_set(){
        Set names = new HashSet()
        names.add("Mary")
        names.add("Zheng")
        names.each { println it}
    }
 
    @Test
    public void each_in_collection_person(){
        Person [] persons  = [new Person("Mary", "Zheng"), new Person("Alex", "Zheng"), new Person("Allen", "Zheng")]
        persons.each { println it}
    }
 
    @Test
    public void each_in_collection_mixObject(){
        def items  = [new Person("Mary", "Zheng"), "this is string", 100]
        items.each { println it}
    }
}

Output of each_in_collection_array for an array of String.

Output from each_in_collection_array

1
2
3
4
Mary
Becky
Susan
Tom

Output of each_in_collection_map for a map.

Output from each_in_collection_map

1
2
3
4
id001=Mary
id002=Alex
id003=Allen
id004=Sammo

Output of each_in_collection_person for a List of Person.

Output from each_in_collection_person

1
2
3
jcg.zheng.demo.groovy.Person(Mary, Zheng)
jcg.zheng.demo.groovy.Person(Alex, Zheng)
jcg.zheng.demo.groovy.Person(Allen, Zheng)

Output of each_in_collection_mixObject for a collection with a Person, String and number.

Output from each_in_collection_mixObject

1
2
3
jcg.zheng.demo.groovy.Person(Mary, Zheng)
this is string
100

3.5 EachWithIndex for a Collection

Groovy also defines eachWithIndex as the default method:

Object eachWithIndex(Closure closure): Iterates through an aggregate type or data structure, passing each item and the item’s index (a counter starting at zero) to the given closure.

In this step, we will create EachWithIndexDemo with eachWithIndex .

EachWithIndexDemo.groovy

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package jcg.zheng.demo.groovy
 
import static org.junit.Assert.*
 
import org.junit.Test
 
class EachWithIndexDemo {
 
    @Test
    public void each_in_collection_array(){
        String[] names = ["Mary", "Becky", "Susan", "Tom"]
        names.eachWithIndex { name, i -> println "${i} = ${name}"}
    }
 
    @Test
    public void each_in_collection_list(){
        List names = ["Mary", "Becky", "Susan", "Tom"]
        names.eachWithIndex {  name, i -> println "${i} = ${name}"}
    }
 
    @Test
    public void each_in_collection_map(){
        def names  = [:]
        names["id001"]= "Mary"
        names["id002"]= "Alex"
        names["id003"]= "Allen"
        names["id004"]= "Sammo"
        names.eachWithIndex { name, i -> println "${i} = '${name}'"}
    }
 
    @Test
    public void each_in_collection_range(){
        def numbers  = (1..10)
        numbers.eachWithIndex { number, i -> println  "${i} = ${number}"}
    }
 
    @Test
    public void each_in_collection_set(){
        Set names = new HashSet()
        names.add("Mary")
        names.add("Mary")
        names.add("Zheng")
        names.eachWithIndex {   name, i -> println "${i} = '${name}'"}
    }
 
    @Test
    public void each_in_collection_object(){
        Person [] persons  = [new Person("Mary", "Zheng"), new Person("Alex", "Zheng"), new Person("Allen", "Zheng")]
        persons.eachWithIndex {  name, i -> println "${i} = '${name}'"}
    }
 
    @Test
    public void each_in_collection_mixObject(){
        def items  = [new Person("Mary", "Zheng"), "this is string", 100, 1000000L, true, 12.234,]
        items.eachWithIndex { name, i -> println "${i} is ${name.getClass()}, content= '${name}' "}
    }
}

We will only print out the each_in_collection_mixObject as an example.

Output from each_in_collection_mixObject

1
2
3
4
5
6
0 is class jcg.zheng.demo.groovy.Person, content= 'jcg.zheng.demo.groovy.Person(Mary, Zheng)'
1 is class java.lang.String, content= 'this is string'
2 is class java.lang.Integer, content= '100'
3 is class java.lang.Long, content= '1000000'
4 is class java.lang.Boolean, content= 'true'
5 is class java.math.BigDecimal, content= '12.234'

4. Demo

Execute all three unit tests and captured the screenshot:

Figure 1 Demo Each Method

5. Groovy Each – Summary

In this example, we demonstrated the each and  eachWithIndex  methods for String, number,Object, and a collection of list, map, set, and range.

6. Download the Source Code

This example consists of a Maven project which demonstrates the usage of Groovy each method for various object types.

Download
You can download the full source code of this example here: Groovy Each Example

Mary Zheng

Mary has graduated from Mechanical Engineering department at ShangHai JiaoTong University. She also holds a Master degree in Computer Science from Webster University. During her studies she has been involved with a large number of projects ranging from programming and software engineering. She works as a senior Software Engineer in the telecommunications sector where she acts as a leader and works with others to design, implement, and monitor the software solution.
Subscribe
Notify of
guest


This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button