Groovy

Groovy List Example

1. Introduction

List is generally used as stack in software development world in order to push items in it for future use and to be able to fetch back in a desired way. In this tutorial, I will show you how to use Groovy list like a senior developer. I assume, you have already set up Groovy on local machine and executed Hello World project. So, let’s get started

2. List Declaration

In groovy, you can declare list with zero item and then add item or you can declare list with initial items. Additionally, you can provide default value to list to return default value on case of index not found. Let’s look at following example to see how it is used in real life.

 
GroovyListDeclaration.groovy

package com.javacodegeeks.groovy.list

class GroovyListDeclaration {

	static main(args) {
		def cartoons = []
		cartoons[0] = 'Regular Show'
		cartoons[1] = 'Adventure Time'
		println cartoons // [Regular Show, Adventure Time]
		
		def cartoonsWithInitialItems = ['The Amazing World of Gumball', 'Johnny Bravo']
		println cartoonsWithInitialItems // [The Amazing World of Gumball, Johnny Bravo]
		
		def cartoonsWithDefault = ['Johnny Test', 'Batman', 'Scooby Doo'].withDefault { 'Smurfs' }
		println cartoonsWithDefault[1] // Batman
		println cartoonsWithDefault[4] // Smurfs
	}

}

If I simply explain what is going on above, in line 06 empty list is declared(square brackets are used for list in Groovy). On line 07 and 08 items added to list by using their indexes. On line 11 a list is declared with initial values. Finally, on line 14 we have applied extra function to list called withDefault in order to return default value in case of provided index is not found. On line 15 it returns Batman, because provided index exists in the list. However, on line 16 it returns Smurfs which is default value of list for non-existent indexes.

3. Add Items

In general, we need to add items to the list to use in the feature, and there are also several ways to add items to list in groovy. You can have a look at following example to see the way items added to list.

GroovyAddItems.groovy

package com.javacodegeeks.groovy.list

package com.javacodegeeks.groovy.list

class GroovyListAddItems {

	static main(args) {
		def cartoons = ['Regular Show', 'The Amazing World of Gumball']
		cartoons.push('Adventure Time')
		cartoons[3] = 'Batman'
		cartoons << 'Smurfs'
		println cartoons // [Regular Show, The Amazing World of Gumball, Adventure Time, Batman, Smurfs]
		
		cartoons.plus(4, 'Scooby Doo')
		println cartoons // [Regular Show, The Amazing World of Gumball, Adventure Time, Batman, Smurfs]
		
		def cartoonsWithPlus = cartoons.plus(2, 'Scooby Doo')
		println cartoonsWithPlus // [Regular Show, The Amazing World of Gumball, Scooby Doo, Adventure Time, Batman, Smurfs]
		
		cartoons.add(0, 'Johnny Test')
		println cartoons // [Smurfs, Regular Show, The Amazing World of Gumball, Adventure Time, Batman, Johnny Test]
		
		cartoons.addAll(2, ['Tom and Jerry', 'Uncle Grandpa']) // [Smurfs, Regular Show, Tom and Jerry, Uncle Grandpa, The Amazing World of Gumball, Adventure Time, Batman, Smurfs]
		println cartoons
	}

}

In above example, after declaring our list on line 06 we added three items to list. push, and << adds the item at the end to the list. Also, you can add item by providing index as on line 10. By adding operation, we changed the original list. On line 11, you can see plus function, and this function is also add items to list without changing original list. You can think that like concatenation. That is why the outputs on line 09 and 12 are same. In example, we have provided a starting index for item to plus function for insert item in desired place. If you do not provide index, it will add it to end of the list. On line 18 and 20 item or items are added to desired place in the list.

4. Remove Items

You can remove items from list by using remove() or pop(). Following example will explain the removal part for you.

GroovyRemoveItems.groovy

package com.javacodegeeks.groovy.list

class GroovyListRemoveItems {

	static main(args) {
		def cartoons = ['Regular Show', 'The Amazing World of Gumball', 'Adventure Time']
		def poppedElement = cartoons.pop() 
		println poppedElement // Adventure Time
		println cartoons // [Regular Show, The Amazing World of Gumball]
		
		cartoons.remove(0)
		println cartoons // [The Amazing World of Gumball]
		
	}

}

When you use pop() it will remove last element and also return popped element. Also, you can use remove() by providing desired index.

5. Item Lookup

Sometimes, we want to search items in a list or filter items according to criteria in order to get output for your application. This kind of operations are very easy and groovy, and you will see that it is very friendly to use something like speaking in english. So, let’s do some practises.

GroovyLookupItems.groovy

package com.javacodegeeks.groovy.list

class GroovyLookupItems {

	static main(args) {
		def cartoons = [
				'Regular Show',
				'The Amazing World of Gumball',
				'Adventure Time',
				'Uncle Grandpa',
				'Batman',
				'Scooby Doo'
			]
		def scoobyDoo = cartoons.find { it == 'Scooby Doo' }
		println scoobyDoo // Scooby Doo
		
		def cartoonNamesWithSizeGreaterThan12 = cartoons.findAll { it.size() > 12 }
		println cartoonNamesWithSizeGreaterThan12 // [The Amazing World of Gumball, Adventure Time, Uncle Grandpa]
		
		def cartoonNamesWithSizeGreaterThan15 = cartoons.findAll { cartoon -> cartoon.size() > 15 }
		println cartoonNamesWithSizeGreaterThan15 // [The Amazing World of Gumball]
		
		def cartoonsFoundWithRegex = cartoons.findAll { it =~ /an/ }
		println cartoonsFoundWithRegex // [Uncle Grandpa, Batman]
		
		def cartoonIndexList = cartoons.findIndexOf { it =~ /^A/ }
		println cartoonIndexList // 2
		
		def cartoonIndexListWithStartPoint = cartoons.findIndexOf(4) { it =~ /^A/ }
		println cartoonIndexListWithStartPoint // -1
		
		def cartoonLastIndex = cartoons.findLastIndexOf { it.size() > 10 }
		println cartoonLastIndex // 3
	}

}

In above example, as you can see on line 14 we used find function for predefined list. Inside the find function we provided our criteria, but what is the it there? Actually, it is the current element at a time while you are iterating the list. You don’t need to use it. You can alias it with any name you desired. You can refer to line 20 for how to alias(or override you can say) it with cartoon which is refers to current cartoon at a time. If we come back to find part, be careful about that if you want find it will return first found result from list. On the other hand, if you use findAll as on line 20, it will return the list of found results. On line 20 we are saying that give me the cartoons that has character length bigger than 15. You can also use regex to find your result from list. When you look at line 23, you will know that it will return the cartoon list that has an inside its name. Sometimes, you may want to return index instead of item itself. You can see on line 26, it will return the cartoon index list with a name starts with A. While searching for specific item index, you can provide starting point. For example, on line 29, even though there is an item in list with starts with A (Adventure Time), it couldn’t be found. Since, we have made search in the list after the index 4. Finally, you can find last index of the index list founded by your criteria like on line 32

6. Split List

In this section, we will create sublist of our entire list. For example, you can see below example for how to split list in to sublist.

GroovyListSplit.groovy

package com.javacodegeeks.groovy.list

class GroovyListSplit {
	
	static main(args) {
		def cartoons = [
				'Regular Show',
				'The Amazing World of Gumball',
				'Adventure Time',
				'Uncle Grandpa',
				'Batman'
			]
		
		def cartoonsSplitListWithTwoCartoonEach = cartoons.collate(2)
		println cartoonsSplitListWithTwoCartoonEach // [[Regular Show, The Amazing World of Gumball], [Adventure Time, Uncle Grandpa], [Batman]]
		
		def cartoonsSplitListWithThreeCartoonEach = cartoons.collate(3)
		println cartoonsSplitListWithThreeCartoonEach // [[Regular Show, The Amazing World of Gumball, Adventure Time], [Uncle Grandpa, Batman]]
		
		def cartoonsSplitListWithoutRemainder = cartoons.collate(2, false)
		println cartoonsSplitListWithoutRemainder // [[Regular Show, The Amazing World of Gumball], [Adventure Time, Uncle Grandpa]]
	}

}

We have used collate function here and this function accepts two parameters. First one is for number of element on each sub list. Second one is for showing remainder or not. For example on line 15, there is one cartoon (Batman) in remainder with size one. If you do not want to show remainder in the result, you can use code like on line 20

7. Count

In order to know size of the list, you can use size() function. If you want to learn occurence of the item in a list, you can use count(). You can refer following example to understand case better.

GroovyListCount.groovy

package com.javacodegeeks.groovy.list

class GroovyListCount {
	
	static main(args) {
		def cartoons = [
				'Regular Show',
				'The Amazing World of Gumball',
				'Adventure Time',
				'Regular Show',
				'Adventure Time',
				'Adventure Time'
			]
		def cartoonCount = cartoons.size()
		println cartoonCount // 6
		
		def advTimeCount = cartoons.count('Adventure Time')
		println advTimeCount // 3
		
		def regShowCount = cartoons.count('Regular Show')
		println regShowCount // 2
	}

}

8. Apply

If you want to apply some functions or operations to each element in a list, Groovy is the right language you can choose to perform it easily. For example, converting all the characters of the item that starts with A in a list. You can have a look at following examples to see how it can be applied.

GroovyListApply.groovy

package com.javacodegeeks.groovy.list

class GroovyListApply {
	
	static main(args) {
		def self = new GroovyListApply()
		def cartoons = [
				'Regular Show',
				'The Amazing World of Gumball',
				'Adventure Time'
			]
		def cartoonsWithUpperCase = cartoons*.toUpperCase()
		println cartoonsWithUpperCase // [REGULAR SHOW, THE AMAZING WORLD OF GUMBALL, ADVENTURE TIME]
		
		def cartoonStartsAToUppercase = cartoons.collect { cartoon -> self.uc(cartoon) }
		println cartoonStartsAToUppercase // [Regular Show, The Amazing World of Gumball, ADVENTURE TIME]
	}

	def uc(String cartoon) {
		if (cartoon =~ /^A/ ) cartoon.toUpperCase()
		else cartoon
	}
}

In above example, on line 12 we have applied toUpperCase() function to each element. You can be careful about *, and this means apply upper case to every element of list. On line 15, we are applying the custom function uc to every list element by first collecting with collect() and aliasing it to cartoon and pass it to the uc function.

9. Conclusion

All the sections above are the basic level list usage of the Groovy. We have declared Groovy list, added/removed items. Also, we have search items in list by providing some criteria. In case of need, we split list into sub lists. Finally, we count list items and applied some functions to list elements. List usage is bounded with your dream power, and you can level up your list usage also Groovy development if you do more practices about Groovy lists.

Download
You can download the full source code of the project here: GroovyListExample

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