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

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<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

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

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

100

Output from each_in_string for “Hello World!”

Output from each_in_string

H
e
l
l
o
 
W
o
r
l
d
!

Output from each_in_object for a Person.

Output from each_in_object

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

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

Mary
Becky
Susan
Tom

Output of each_in_collection_map for a map.

Output from each_in_collection_map

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

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

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

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

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
Inline Feedbacks
View all comments
Back to top button