
- Groovy Tutorial
- Groovy - Home
- Groovy - Overview
- Groovy - Environment
- Groovy - Basic Syntax
- Groovy - Data Types
- Groovy - Variables
- Groovy - Optionals
- Groovy - Numbers
- Groovy - Strings
- Groovy - Ranges
- Groovy - Lists
- Groovy - Maps
- Groovy - Dates & Times
Groovy Operators
- Groovy - Operators
- Groovy - Arithmetic Operators
- Groovy - Assignment Operators
- Groovy - Relational Operators
- Groovy - Logical Operators
- Groovy - Bitwise Operators
- Groovy - Spaceship Operator
- Groovy - in Operator
- Groovy - Elvis Operator
- Groovy - Safe Navigation Operator
- Groovy Operator Precedence & Associativity
Control Statements
- Groovy - Decision Making
- Groovy - If Else Statement
- Groovy - Switch Statement
- Groovy - Loops
- Groovy - For Loop
- Groovy - For-in Loop
- Groovy - While Loop
- Groovy - Do While Loop
- Groovy - Break Statement
- Groovy - Continue Statement
Groovy File Handling
- Groovy - File I/O
- Java - Create a File
- Java - Write to File
- Java - Append to File
- Java - Read Files
- Java - Delete Files
- Java - File Properties
- Java - File Existence and Type
- Java - File Size
- Java - File Permissions
- Java - Directories
- Java - Listing Directories
- Java - Filtering Files/Directories
- Java - Deleting Directories
- Java - Renaming Files/Directories
Groovy Error & Exceptions
- Groovy - Exception Handling
- Groovy - try-catch Block
- Groovy - try-with-resources
- Groovy - Multi-catch Block
- Groovy - Nested try Block
- Groovy - Finally Block
- Groovy - throw Exception
- Groovy - Exception Propagation
- Groovy - Built-in Exceptions
- Groovy - Custom Exception
Groovy Multithreading
- groovy - Multithreading
- groovy - Thread Life Cycle
- groovy - Creating a Thread
- groovy - Starting a Thread
- groovy - Joining Threads
- groovy - Naming Thread
- groovy - Thread Scheduler
- groovy - Thread Pools
- groovy - Main Thread
- groovy - Thread Priority
- groovy - Daemon Threads
- groovy - Shutdown Hook
Groovy Synchronization
- groovy - Synchronization
- groovy - Block Synchronization
- groovy - Static Synchronization
- groovy - Inter-thread Communication
- groovy - Thread Deadlock
- groovy - Interrupting a Thread
- groovy - Thread Control
- groovy - Reentrant Monitor
- Groovy - Methods
- Groovy - Methods
- Groovy - Optional parenthesis
- Groovy - Named Arguments
- Groovy - Closures as Arguments
- Groovy - Method Overloading
- Groovy - Method Scope and Visibility
- Groovy - isCase Method
- Groovy - Implicit Return
- Groovy - Variable Arguments
- Groovy - Regular Expressions
- Groovy - Regular Expressions
- Groovy - Defining Regular Expressions
- Groovy - Matcher Object
- Groovy - Regex Tasks
- Groovy - XML
- Groovy - XML
- Groovy - Parsing XML
- Groovy - Creating XML
- Groovy - Modifying XML
- Groovy - Querying XML
- Groovy - Simplified Notation
- Groovy - Closure based Querying
- Groovy - Closure based Creation
- Groovy - JSON
- Groovy - JSON
- Groovy - Parsing JSON
- Groovy - Creating JSON using JsonOutput
- Groovy - Creating JSON using JsonBuilder
- Groovy - Modifying JSON
- Groovy - Error Handling
- Groovy - Handling JSON Arrays
- Groovy - JSON Array Operations
- Groovy - JSON Objects
- Groovy - JSON Object Operations
- Groovy - Generics
- Groovy - Generics
- Groovy - Declaring Generic Types
- Groovy - Bound Type Parameters
- Groovy - Wild Cards
- Groovy - Miscellaneous
- Groovy - Object Oriented
- Groovy - Closures
- Groovy - Annotations
- Groovy - JMX
- Groovy - DSLS
- Groovy - Database
- Groovy - Builders
- Groovy - Command Line
- Groovy - Unit Testing
- Groovy - Template Engines
- Groovy - Meta Object Programming
- Groovy Useful Resources
- Groovy - Quick Guide
- Groovy - Useful Resources
- Groovy - Discussion
Groovy - Maps
A Map (also known as an associative array, dictionary, table, and hash) is an unordered collection of object references. The elements in a Map collection are accessed by a key value. The keys used in a Map can be of any class. When we insert into a Map collection, two values are required: the key and the value.
Following are some examples of maps −
[TopicName : Lists, Author : Raghav] Collections of key value pairs which has TopicName as the key and their respective values.
[ : ] An Empty map.
In this chapter, we will discuss the map methods available in Groovy.
Sr.No. | Methods & Description |
---|---|
1 |
any(Closure predicate)
Iterates over the entries of the map and checks if predicate is valid for at least one of the entry. |
2 |
asBoolean()
Coerces the map to boolean value. Empty Map returns false and non-empty is coerced to true. |
3 |
asImmutable()
Returns an unmodifiable view of the map. |
4 |
asType(Class clazz)
Coerces the map to given type. Map keys are used as public method names and values are as implementation of those methods. |
5 |
asUnmodifiable()
Returns an unmodifiable view of the map. |
6 |
collect(Closure transform)
Iterates through the Map entries and transform them using transform closure to return a List of transformed values. |
7 |
collect(Object collector, Closure transform)
Iterates through the Map entries and transform them using transform closure to return a Collector with transformed values. |
8 |
collectEntries(Closure transform)
Iterates through the Map entries and transform them using transform closure to return a Map of transformed entries. |
9 |
collectEntries(Map collector, Closure transform)
Iterates through the Map entries and transform them using transform closure to return a Map with transformed entries. |
10 |
collectMany(Closure projection)
Iterates through the Map entries and flattens the resultant collections adding them to a collection. |
11 |
collectMany(Object collector, Closure projection)
Iterates through the Map entries and flattens the resultant collections adding them to a passed collector. |
12 |
count(Closure closure)
Returns the count of occurences of items of the map which satisfies the given closure. |
13 |
count(Object initialCount, Closure closure)
Returns the initialcount + count of occurences of items of the map which satisfies the given closure. |
14 |
count(Closure closure)
Groups the members of the map into groups determined by the mapping closure and by counting the frequency of created groups. |
15 |
containsKey()
Does this Map contain this key? |
16 |
drop(int num)
Drops given number of key-value pairs from the map from the head of the map if available. |
17 |
dropWhile(Closure closure)
Drops key-value pairs from the map from the head of the map if they satisfy the condition imposed by the closure. |
18 |
each(Closure closure)
Allows map to be iterated using passed closure. |
19 |
eachWithIndex(Closure closure)
Allows map to be iterated using passed closure while closure accepting the index of the entry as well. |
20 |
equal(Map map)
Compares two maps by coercing numerical values as identical. |
21 |
every(Closure predicate)
Iterates over the entries of the map to check if predicate is true for all entries. |
22 |
find(Closure predicate)
Finds and returns the first entry matching the provided predicate. |
23 |
findAll(Closure predicate)
Finds and returns the all entries matching the provided predicate. |
24 |
findResult(Closure predicate)
Finds and returns first matching non-null result by passing each entry to the closure, otherwise null is returned. |
25 |
findResult(Object defaultResult, Closure predicate)
Finds and returns first matching non-null result by passing each entry to the closure, otherwise defaultResult is returned. |
26 |
findResults(Closure filteringTransform)
Finds and returns first matching non-null result by passing each entry to the closure, otherwise defaultResult is returned. |
27 |
get(Object key)
Look up the key in this Map and return the corresponding value. If there is no entry in this Map for the key, then return null. |
28 |
get(Object key, Object defaultValue)
Look up the key in this Map and return the corresponding value. If there is no entry in this Map for the key, then return defaultValue. It also adds the defaultValue and Key to the Map. |
29 |
getAt(Object key)
Supports subscript operator for a map. |
30 |
groupBy(Closure closure)
Groups the members of a map into sub maps determined by the supplied mapping closure. |
31 |
groupBy(Object closures)
Groups the members of a map into sub maps determined by the supplied mapping closures. |
32 |
groupBy(List closures)
Groups the members of a map into sub maps determined by the supplied mapping closures. |
33 |
groupEntriesBy(Closure closure)
Groups the entries of a map into sub maps determined by the supplied mapping closure. |
34 |
intersect(Map right)
Returns a Map which is intersection of the both maps that is a map of common entries. |
35 |
keySet()
Obtain a Set of the keys in this Map. |
36 |
leftshift(Map other)
Overloads the left shift operator provides an easy way to insert one map entries into the map. |
37 |
leftshift(Entry entry)
Overloads the left shift operator provides an easy way to insert an entry into the map. |
38 |
max(Closure closure)
Select an entry in a map having maximum calculated using closure passed. |
39 |
min(Closure closure)
Select an entry in a map having minimum calculated using closure passed. |
40 |
minus(Map removeMe)
Creates and returns a Map composed on entries of first map minus entries of the given map. |
41 |
plus(GString right)
Appends a GString to the literal of the Map instance. |
42 |
plus(String right)
Appends a String to the literal of the Map instance. |
43 |
plus(Collection entries)
Returns a new map containing all entries from self and passed collection. |
44 |
plus(Map entries)
Returns a new map containing all entries from self and passed map. |
45 |
putAll(Collection entries)
Provides an easier way to add multiple Map.Entry values to the map. |
46 |
putAt(Object key, Object value)
Provides a helper method to allow a Map to work with subscript operators. |
47 |
put()
Associates the specified value with the specified key in this Map. If this Map previously contained a mapping for this key, the old value is replaced by the specified value. |
48 |
removeAll(Closure closure)
Removes entries from the Map which satisfy the given closure. |
49 |
retainAll(Closure closure)
Retains entries from the Map which satisfy the given closure and removes other entries from the map. |
50 |
reverseEach(Closure closure)
Iterates a Map in reverse order using provided closure. |
51 |
size()
Returns the number of key-value mappings in this Map. |
52 |
sort()
Sorts the map using natural ordering of the keys and returns the sorted map. Original map is unaffected. |
53 |
sort(Closure closure)
Sorts the map using the closure passed and returns the sorted map. Original map is unaffected. |
54 |
sort(Comparator comparator)
Sorts the map using the comparator passed and returns the sorted map. Original map is unaffected. |
55 |
subMap(Object[] keys)
Creates a new map based on the keys passed. Original map is unaffected. |
56 |
subMap(Collection keys)
Creates a new map based on the keys passed. Original map is unaffected. |
57 |
take(int num)
Returns a new map containing first num elements of the map. |
58 |
takeWhile(Closure condition)
Returns a new map containing elements of the map starting from head of the map until the condition specified by closure fails. |
59 |
toMapString()
Returns the string representation of the map. |
60 |
toMapString(int maxSize)
Returns the string representation of the map while limiting the string representation using maxSize. |
61 |
toSorted()
Sorts the elements of given map using NumberAwareComparator on map entry values to determine the resulting order or by natural ordering of Map.Entry values. |
62 |
toSorted(Closure condition)
Sorts the elements of given map using supplied closure as a comparator to determine the ordering. |
63 |
toSorted(Comparator comparator)
Sorts the elements of given map using supplied comparator to determine the ordering. |
64 |
values()
Returns a collection view of the values contained in this Map. |
Example - Checking key from a Map of String and String
Following is an example of the usage of this method −
main.groovy
// define a map def map = ["TopicName" : "Maps", "TopicDescription" : "Methods in Maps"] // check if keys exist println(map.containsKey("TopicName")) println(map.containsKey("Topic"))
Output
When we run the above program, we will get the following result −
true false
Example - Getting Value based on key from a Map of String and String
Following is an example of the usage of this method −
main.groovy
// define a map def map = ["TopicName" : "Maps", "TopicDescription" : "Methods in Maps"] // get the value if key is present println(map.get("TopicName")) println(map.get("Topic"))
Output
When we run the above program, we will get the following result −
Maps null
Example - Getting Set of Keys from a Map of String and String
Following is an example of the usage of this method −
main.groovy
// define a map def map = ["TopicName" : "Maps", "TopicDescription" : "Methods in Maps"] // get the set of keys println(map.keySet())
Output
When we run the above program, we will get the following result −
[TopicName, TopicDescription]