Kotlin HashMap
A HashMap in Kotlin is a collection of key-value pairs, where each key must be unique. In this tutorial, we'll cover the basics of creating and using HashMaps in Kotlin.
Syntax
To create a HashMap in Kotlin, use the following syntax:
val hashMap: HashMap<KeyType, ValueType> = HashMap()
Where KeyType
and ValueType
are the types of keys and values, respectively.
To add elements to the HashMap, you can use the put()
method like this:
hashMap.put(key, value)
Example
Here's an example of creating and using a HashMap in Kotlin:
fun main() {
val products = HashMap<Int, String>()
products.put(101, "Keyboard")
products.put(102, "Mouse")
products.put(103, "Monitor")
println(products)
products[104] = "Headphones"
println(products)
products.remove(103)
println(products)
}
Output:
{101=Keyboard, 102=Mouse, 103=Monitor}
{101=Keyboard, 102=Mouse, 103=Monitor, 104=Headphones}
{101=Keyboard, 102=Mouse, 104=Headphones}
Explanation
In the example above, we first created a HashMap called products
that stores pairs of integers and strings where the integers represent product IDs and the strings represent the names of those products.
We added three elements to the HashMap using the put()
method and printed the HashMap using println()
.
We then added another element to the HashMap using the square bracket notation []
and printed the HashMap again.
Finally, we removed an element from the HashMap using the remove()
method and printed the HashMap one more time.
Use
HashMaps can be used in a variety of scenarios, including:
- Storing and retrieving data efficiently.
- Counting the frequency of items.
- Grouping items by a specific category or attribute.
Important Points
- Keys in a HashMap must be unique.
- You can use the
put()
method or the square bracket notation[]
to add elements to the HashMap. - Use the
remove()
method to remove elements from the HashMap. - Use the
size
property to get the number of elements in the HashMap.
Summary
In this tutorial, we covered the basics of creating and using HashMaps in Kotlin. We discussed the syntax for creating HashMaps, adding and removing elements, and printing the contents using println()
. We also talked about some common use cases for HashMaps and important points to keep in mind when using them.