We can use the remove
method to remove an entry from the HashMap
.
fun remove(key: K): V?
The key of the entry to be removed from the HashMap
is passed as an argument.
If the HashMap
contains an entry for the provided argument then the value of the entry is returned. Otherwise, null
is returned.
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 valuevar map : HashMap<String, Int> = HashMap<String, Int> ()// add two entriesmap.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")}
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.