Skip to Content
Learn
Maps
Adding and Removing Entries

Since a mutable map supports read and write operations, we are able to manipulate its contents by adding or removing key-value pairs.

Assume we have the following mutable map that stores a country’s national tree:

var nationalTrees = mutableMapOf("Italy" to "Strawberry Tree", "Greece" to "Olive", "Romania" to "Oak", "Canada" to "Maple")

We can utilize Kotlin’s built-in put() function to add a new entry to the mutable map:

nationalTrees.put("Albania", "Olive")

Within the parentheses of the put() function, we’ve placed the key followed by a comma and the value. The key-value pair will be added to the end of the map.

Say that for our program, we only need to track national trees in Europe. To remove "Canada" from the map, we can use the remove() function:

nationalTrees.remove("Canada")

Notice how we only need to specify the unique identifier, or key, for the pair rather than the entire entry.

Outputting the final map with a println() statement will result in:

{Italy=Strawberry Tree, Greece=Olive, Romania=Oak, Albania=Olive}

Explore the other various map-specific operations here, as well as other general map supported functionalities in Kotlin’s documentation.

Instructions

1.

In Paintings.kt, we’ve populated a mutable map of famous paintings in MoMa and their painters. We’ll use our knowledge of adding and removing entries to update this map.

The if expression utilizes one of map’s built-in functions, containsValue(), to check if a painting by Claude Monet does not exist in the map.

Within its body, use another function to add, "Water Lillies", painted by Claude Monet to the map.

2.

The Mona Lisa permanently resides at The Louvre in Paris, France, and not at the MoMA. Remove the key-value pair associated with this painting.

On the following line, use a print statement to output the final map.

Folder Icon

Take this course for free

Already have an account?