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 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")
map.clear();
println("The map is : $map")
}

Explanation

  • Line 3: We create a new HashMap object named map.
  • Lines 5–7: We add three entries to the map, {one=1,two=2,three=3}, using the put method.
  • Line 11: We use the map object’s clear method. This removes all the entries of the map. Now, the map becomes empty {}.

Free Resources