How to remove all entries of HashMap in Kotlin
Overview
The clear method removes all entries of HashMap.
Syntax
fun clear()
Argument
This method doesn’t take any argument.
Return value
This method doesn’t return any value.
Code
The code below demonstrates how to remove all entries of 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")map.clear();println("The map is : $map")}
Explanation
- Line 3: We create a new
HashMapobject namedmap. - Lines 5–7: We add three entries to the
map,{one=1,two=2,three=3}, using theputmethod. - Line 11: We use the
mapobject’sclearmethod. This removes all the entries of themap. Now, the map becomes empty{}.