Groovy

Groovy Collect Example

1. Introduction

Groovy collect() is used for iterate through collections to apply closure to each element. In this tutorial, we will see how to use collect() for collection operations. Let’s get started

2. Collect

When you have a look at the method signatures of collect below, we will see that collect can be executed with default closure which is Closure.IDENTITY, with a closure, or with a supplied collector and closure

Overloaded Methods

public List collect()
public List collect(Closure transform)
public Collection collect(Collection collector, Closure transform)

 
Let say that you have a list of fruits and you want to apply uppercase operation to each element of fruit list. You can do that by following code.

GroovyCollect.groovy

package com.javacodegeeks.groovy.collect

class GroovyCollect {

	static main(args) {
		def fruits = ["Banana", "Apple", "Grape", "Pear"]
		def upperCaseFruits = fruits.collect { it.toUpperCase() }
		println upperCaseFruits // [BANANA, APPLE, GRAPE, PEAR]
	}

}

As you can see on line 07, upperCase() function applied to each element, and it there means current element while iterating. As we said above, collect function takes closure as parameter and our closure here is { it.toUpperCase() }. Let me give you another example. You have Fruit class and you want to construct Fruit object list by using fruit list. You can do that by simply apply new Fruit object creation closure to the collect function. You can see example below.

GroovyCollectForClass.groovy

package com.javacodegeeks.groovy.collect

import groovy.transform.ToString

class GroovyCollectForClass {

	static main(args) {
		def fruits = ["Banana", "Apple", "Grape", "Pear"]
		def fruitObjects = fruits.collect { new Fruit(name: it) }
		println fruitObjects // [com.javacodegeeks.groovy.collect.Fruit(name:Banana, amount:0), com.javacodegeeks.groovy.collect.Fruit(name:Apple, amount:0), com.javacodegeeks.groovy.collect.Fruit(name:Grape, amount:0), com.javacodegeeks.groovy.collect.Fruit(name:Pear, amount:0)]
	}

}

@ToString(includeNames = true)
class Fruit {
	def name
	def amount = 0
}

On line 16, we have declared a class with an annotation @ToString(includeNames = true) to show field names to be shown when we print class object. After class declaration, we apply object creation new Fruit(name: it) on line 09. While iterating fruit elements, the closure will be like this, new Fruit(name: "Banana"), new Fruit(name: "Apple"), new Fruit(name: "Grape"), new Fruit(name: "Pear")

3. Collect with Supplied Collector

Sometimes, you may need to start collect operation wiht an initial list, or whenever you collect an element, you may need to add it to different type of collection instead of list. In that case, you can use a supplementary collectors beside the closure in side collect() function. Let say that, you have initial fruit list, and you wan to collect another fruit list by providing initial fruit list to collect function as supplementary collector. You can see following example to understand what is going on.

GroovyCollectWithCollector.groovy

package com.javacodegeeks.groovy.collect

class GroovyCollectWithCollector {

	static main(args) {
		def initialFruits = ["Orange", "Lemon"]
		def fruits = ["Banana", "Apple", "Grape", "Pear"]
		def totalFruits = fruits.collect(initialFruits, { it.toUpperCase() })
		
		println totalFruits // [Orange, Lemon, BANANA, APPLE, GRAPE, PEAR]
		println initialFruits // [Orange, Lemon, BANANA, APPLE, GRAPE, PEAR]
	}

}

As you can see on line 10, collect operation started with initialFruits and closure applied to fruits elements. When you supply a collector to collect() function, you will get a modified version of the collector as you can see on line 11. initialFruits list has also changed, because it is the collector we supplied and collect result will be populated in that variable..

Let say that, you have list of fruits like below.

def fruits = ["Banana", "Apple", "Grape", "Pear", "Banana"]

and you want to get distinct value of fruits. You can do that by using following.

GroovyCollectWithCollectorDistinct.groovy

package com.javacodegeeks.groovy.collect

class GroovyCollectWithCollectorDistinct {

	static main(args) {
		def fruits = ["Banana", "Apple", "Grape", "Pear", "Banana"]
		def distinctFruits = fruits.collect(new HashSet(), { it })
		
		println distinctFruits // [Apple, Pear, Grape, Banana]
	}

}

While you are iterating elements with collect() on line 07, collected elements will be added to collector, and that collector is a HashSet(). This collection type is for keeping distinct values as you may already remember from Java.

4. Conclusion

Groovy has powerful components for the Collections SDK, and one of them is collect(). By using collect(), we have applied closures to list elements. Also, we have used different overloaded functions of collect() function for using default collector, or provide our own collectors like HashSet().

Download
You can download the full source code of this example as an  Eclipse project here: GroovyCollectExample

Huseyin Babal

Huseyin Babal has deep experience in Full Stack Development since 2007. He is mainly developing applications with JAVA, Spring, PHP, NodeJS, AngularJS. He is also interested in DevOps Engineering since 2013 and using AWS, Heroku for Cloud deployment and playing with Docker and Consul for implementing infinite scalable systems. He likes to share his experience in public conferences and perform advanced workshops about Full Stack Development and Devops. He is the author of NodeJS in Action course in Udemy.
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