Kotlin .put()
Published Jan 29, 2023
Contribute to Docs
In Kotlin, the .put() method is used to add a key-value pair to a hash map. It is a member function of the MutableMap interface, which means it can be called on any object that implements this interface, such as a HashMap or LinkedHashMap.
Syntax
myHashMap.put(key, value)
It takes in two parameters:
- The
keyof the key-value pair to add or update in the hash map. - The
valueof the key-value pair to add or update in the hash map.
Example
To add a key-value pair to a HashMap in Kotlin, the .put() method can be used:
fun main() {val map = HashMap<String, Int>()map.put("apple", 1)map.put("banana", 2)map.put("cherry", 3)println(map)}
This will output:
{banana=2, apple=1, cherry=3}
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve 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