Kotlin .remove()

dakshdeepHERE's avatar
Published Feb 7, 2023
Contribute to Docs

The .remove() method is used to remove a key-value pair from a HashMap in Kotlin.

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn Kotlin, the expressive, open-source programming language developed by JetBrains.
    • Beginner Friendly.
      9 hours

Syntax

fun <K, V> MutableMap<K, V>.remove(key: K): V?

It takes one parameter and returns:

  • key: the key of the key-value pair to be removed
  • V? : the value associated with the removed key or null if the key is not found in the map.

Example

Here is an example of how to use the .remove() method in a Kotlin program:

fun main(){
val myMap = hashMapOf("key1" to "value1", "key2" to "value2")
val removedValue = myMap.remove("key1")
print(myMap)
}

The output for the above code will be:

{key2=value2}

All contributors

Contribute to Docs

Learn Kotlin on Codecademy

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn Kotlin, the expressive, open-source programming language developed by JetBrains.
    • Beginner Friendly.
      9 hours