Groovy Quiz 20 | Maps


Reference video | Groovy Playground


1 Point for every correct answer | Let’s Get Started

1.

Is the below information True or False:

Maps is a collection that contains key:value pairs

It is an unordered collection

[key : value]

[‘name’ : ‘Raghav’]

[:] – empty map

 
 

2.

Guess the output

(Can run and check code here – https://groovy-playground.appspot.com/)

def emp = [
    'name' : 'Peter',
    'age'   : 30
    ]
    
println emp.name
println emp['name']
println emp.get('age')
println emp.getAt('age')
 
 
 

3.

def emp = [
    'name' : 'Peter',
    'age'   : 30
    ]
print emp.size()
 
 
 
 

4.

//adding using put
def emp = [
    'name' : 'Peter',
    'age'   : 30
    ]
emp.put('city', 'Boston')
print emp
 
 

5.

//check the presence of a key-value

def emp = [
    'name' : 'Peter',
    'age'   : 30
    ]
emp.put('city', 'Boston')
println emp.containsKey('city')
println emp.containsValue('Boston')
 
 
 

6.

Cloning maps using colone() function

def emp = [
    'name' : 'Peter',
    'age'   : 30
    ]
    
def emp2 = emp.clone()
println emp2
 
 

7.

Iterating a map using closures

def emp = [
    'name' : 'Peter',
    'age'   : 30
    ]
   
emp.each { key,value ->
    println "$key : $value"
}
 
 
 

8.

Iterating with closure along with index position

def emp = [
    'name' : 'Peter',
    'age'   : 30
    ]
    
emp.eachWithIndex { key,value, i ->
    println "$i | $key : $value"
}
 
 
 

9.

Guess the output

def emp = [
    'name' : 'Peter',
    'age'   : 30
    ]
    
emp.each { entry ->
    println "$entry.key : $entry.value"
}
 
 
 

10.

Guess the output

def myMap = ['a' : 1, 'b' : 2]
def entries = myMap.entrySet()
entries.each { entry ->
    println entry.key in ['a', 'b']
    println entry.value in [1, 3]
}
 
 
 
 

11.

def myMap = [‘a’ : 1, ‘b’ : 2]

def entries = myMap.entrySet()
entries.each { entry ->
    println entry.key in ['a', 'b']
    println entry.value in [1, 2, 3]
}
 
 
 
 

12.

def myMap = ['a' : 1, 'b' : 2]
myMap.clear()
print myMap
 
 
 

7