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 {}.
New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources