Home » JVM Languages » Groovy » Groovy Map Example

About Huseyin Babal

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.

Groovy Map Example

In this tutorial, I will show you how to evaluate the power of Groovy maps. You will provided codes for each case and I assume that you have a little bit back ground about groovy. Let’s have a look at map concepts in groovy step by step together.

1. Map Declaration

Maps are generally used for storing key-value pairs in programming languages. You have two options to declare a map in groovy. First option is, define an empty map and put key-value pairs after. Second option is declaring map with default values. You will understand it better if you have a look at example below.
 

 
GroovyMapDeclaration.groovy

package com.javacodegeeks.groovy.map

import groovy.transform.ToString

class GroovyMapDeclaration {

	static main(args) {
		def emptyStudentMap = [:]
		println emptyStudentMap // [:]
		
		def studentMapWithInitialValue = [name: "John", surname: "Doe", age: 17]
		println studentMapWithInitialValue // [name:John, surname:Doe, age:17]
	}
}

Be careful about the colon inside the map declaration. It states that this is a map not a list. You can see that keys are not inside quotes. However, they are all String by default. As you can see, map declaration is very easy stuff, let’s add some values to this map.

2. Map Add Values

You can manipulate groovy maps in several map. When you look at the following examples of adding items to the map,

GroovyMapAddValues.groovy

package com.javacodegeeks.groovy.map

import groovy.transform.ToString

class GroovyMapAddValues {

	static main(args) {
		def student = [:] // Initialize empty map
		student.put('name', 'John') // java notation
		student['surname'] = 'Doe' // You can state key in square brackets
		student << [age: 17] // This is something output redirection in unix commands. key-value pair put inside map object
		student.class = "11C" // Dot notation is also available
		student.'school' = "Groovy School" // Same as previous
		
		println student // [name:John, surname:Doe, age:17, class:11C, school:Groovy School]
	}
}

Above example is for adding values to map, but you can use that commands for updating operation also. For example, if you want to update the age of student, you can use following.

student['age'] = 17 

3. Remove From Map

Removing element from maps is very easy as adding values. In order to remove values from map, you can use different kind of ways. Let’s have a look at following example.

GroovyMapRemove.groovy

package com.javacodegeeks.groovy.map

import groovy.transform.ToString

class GroovyMapRemove {

	static main(args) {
		def student = [name: 'John', surname: 'Doe', age: 17, class: '11C', school: 'Groovy School']
		println student // [name:John, surname:Doe, age:17, class:11C, school:Groovy School]
		
		student.remove('age') // Remove by key
		println student // [name:John, surname:Doe, class:11C, school:Groovy School]
		
		student = student - [school: 'Groovy School'] // This is something like arithmetic operation 
		println student // [name:John, surname:Doe, class:11C]
	}
}

As in the example above, you cna remove elements from map by key or you can simply remove key-value pairs from map with a simple arithmetic like operation. In our case we are substracting [school: 'Groovy School'] and resulting map will be following.

[name: 'John', surname: 'Doe', class: '11C'] // We have removed 'age' and 'school' attribute

4. Map Get Default Value

Sometimes, we need to call some function through an object fetched from map. If the fetched value is null we get NullPointerException. To avoid from getting this exception, we check the returned value from map. What if we get a default value instead of null? Groovy enables you provide default value in case of null value fetched from map. You can see following example for easy understanding.

GroovyMapGetWithDefaultValue.groovy

package com.javacodegeeks.groovy.map

import groovy.transform.ToString

class GroovyMapGetWithDefaultValue {

	static main(args) {
		def student = [name: 'John', surname: 'Doe', age: 17, class: '11C', school: 'Groovy School']
		def result = student.get('teacher', new Teacher(name: "Betty"))
		
		println result // com.javacodegeeks.groovy.map.Teacher(name:Betty)
	}
}

In above example, if student has not a teacher, it will return new Teacher() object, so you can continue your work without thinking about NullPointerException stuff.

5. Map Union

Let say that, you have different kind of information of the student like below.

GroovyMapUnion.groovy

package com.javacodegeeks.groovy.map

import groovy.transform.ToString

class GroovyMapUnion {

	static main(args) {
		def studentProp1 = [name: 'John', surname: 'Doe']
		def studentProp2 = [age: 17, class: '11C']
		def studentProp3 = [school: 'Groovy School']
		def student = studentProp1 + studentProp2 + studentProp3
		
		println student // [name:John, surname:Doe, age:17, class:11C, school:Groovy School]
	}
}

As you can see above, If you need to combine those informations into one variable, you can use following.

def student = studentProp1 + studentProp2 + studentProp3

And resulting map will be like below.

[name: 'John', surname: 'Doe', age: 17, class: '11C', school: 'Groovy School']

6. Map Intersect

Sometimes, you need to find same properties within different maps. For example, you may want to see two students for determining the same properties like below.

GroovyMapIntersect.groovy

package com.javacodegeeks.groovy.map

import groovy.transform.ToString

class GroovyMapIntersect {
	
	static main(args) {
		def student1 = [name: 'John', surname: 'Doe', age: 17]
		def student2 = [surname: 'Bunny', age: 17]
		def sameProperties = student1.intersect(student2) // [age: 17]
		
		println sameProperties // [age:17]
	}
}

When you intersect two maps like above, the same key-value pairse will be fetched from two maps. Both students have surname, and age attributes, but only age attribute will exist in the result because their surnames are different

7. Map Keys and Values

Let say that, you need to know which properties a student have. You can do that with following.

GroovyMapKeys.groovy

package com.javacodegeeks.groovy.map

import groovy.transform.ToString

class GroovyMapKeys {

	static main(args) {
		def student = [name: 'John', surname: 'Doe', age: 17]
        def studentKeys = student.keySet() // [name, surname, age]
		
		println studentKeys // [name, surname, age]
	}
}

In same way, you may want to know about which values a student has. In that case, you can use below.

GroovyMapValues.groovy

package com.javacodegeeks.groovy.map

import groovy.transform.ToString

class GroovyMapValues {

	static main(args) {
		def student = [name: 'John', surname: 'Doe', age: 17]
		def studentValues = student.values() // [John, Doe, 17]
		
		println studentValues // [John, Doe, 17]
	}
}

In order to see overall picture, you can have a look at combined version of the codes for map operations.

GroovyMaps.groovy

package com.javacodegeeks.groovy.map

import groovy.transform.ToString

class GroovyMaps {

	static main(args) {
		// Add values to map
		def student1 = [:] // Initialize empty map
		student1.put('name', 'John') // java notation
		student1['surname'] = 'Doe' // You can state key in square brackets
		student1 << [age: 17] // This is something output redirection in unix commands. key-value pair put inside map object
		student1.class = "11C" // Dot notation is also available
		student1.'school' = "Groovy School" // Same as previous
		
		println "Student 1 info: ${student1}" // Student info: [name:John, surname:Doe, age:17, class:11C, school:Groovy School]
		
		// Remove element from map
		def student2 = [name: 'John', surname: 'Doe', age: 17, class: '11C', school: 'Groovy School']
		student2.remove('age') // Remove by key
		student2 = student2 - [school: 'Groovy School'] // This is something like arithmetic operation
		
		println "Student 2 info: ${student2}" // Student 2 info: [name:John, surname:Doe, class:11C]
		
		// Get default value
		def student3 = [name: 'John', surname: 'Doe', age: 17, class: '11C', school: 'Groovy School']
		def student3Teacher = student3.get('teacher', new Teacher(name: "Betty"))
		
		println "Student 3 teacher info: ${student3Teacher}" // Student 3 teacher info: com.javacodegeeks.groovy.map.Teacher(name:Betty)
		
		// Map union
		def studentProp1 = [name: 'John', surname: 'Doe']
		def studentProp2 = [age: 17, class: '11C']
		def studentProp3 = [school: 'Groovy School']
		def student4 = studentProp1 + studentProp2 + studentProp3
		
		println "Student 4 ingo: ${student4}" // Student 4 ingo: [name:John, surname:Doe, age:17, class:11C, school:Groovy School]
		
		// Map intersect
		def student5 = [name: 'John', surname: 'Doe', age: 17]
		def student6 = [surname: 'Bunny', age: 17]
		def sameProperties = student5.intersect(student6) // [age: 17]
		
		println "Student 5 - Student 6 intersection: ${sameProperties}" // Student 5 - Student 6 intersection: [age:17]
		
		// Map keys and values
		def student7 = [name: 'John', surname: 'Doe', age: 17]
		def student7KeyList = student7.keySet() // [name, surname, age]
		
		println "Student 7 key set: ${student7KeyList}" // Student 7 key set: [name, surname, age]
		
		def student8 = [name: 'John', surname: 'Doe', age: 17]
		def student8ValueList = student8.values() // [John, Doe, 17]
		
		println "Student 8 value set: ${student8ValueList}" // Student 8 value set: [John, Doe, 17]
	}

}

@ToString(includeNames=true, includeFields=true)
class Teacher {
	def name
}

8. Conclusion

Groovy is very good language, because we are able to write and read codes like speaking or writing in English. It has dynamic usage when it comes to coding and this powerful property let us use Groovy maps very easily. Remember that, you need to do lots of practices about Groovy maps in order to get full control Groovy collections. You can try all the examples above online here.

Download
You can download the full source code of the project here: GroovyMapExample
(No Ratings Yet)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar
  Subscribe  
Notify of