How to remove an entry of the HashMap in Kotlin

Overview

We can use the remove method to remove an entry from the HashMap.

Syntax

fun remove(key: K): V?

Parameter

The key of the entry to be removed from the HashMap is passed as an argument.

Return value

If the HashMap contains an entry for the provided argument then the value of the entry is returned. Otherwise, null is returned.

Code

The code below demonstrates how to remove an entry from the HashMap:

fun main() {
//create a new LinkedHashMap which can have String type as key, and int type as value
var map : HashMap<String, Int> = HashMap<String, Int> ()
// add two entries
map.put("one", 1)
map.put("two", 2)
map.put("three", 3)
println("The map is : $map")
var oldValue = map.remove("one");
println("\nmap.remove('one') : ${oldValue}")
println("The map is : $map")
oldValue = map.remove("four");
println("\nmap.remove('four') : ${oldValue}")
println("The map is : $map")
}

Explanation

Line 3: We create a new HashMap object with the name map.

Lines 5 to 7: We add three entries to the map {one=1,two=2,three=3}, using the put method.

Line 11: We use the remove method with one as an argument. This method checks for the entry with the key one. In our map, there is one entry with a key - one so that entry is removed and the value associated with the key is returned. Now the map is {two=2, three=3}.

Line 15: We use the remove method with four as an argument. This method checks for the entry with the key four. In our map, there is no entry with a key four. So null is returned. The map remains unchanged.

Free Resources