Ben Chuanlong Du's Blog

It is never too late to learn.

Hashmap in Kotlin

References

https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-map/index.html#kotlin.collections.Map

  1. LinkedHashMap preserves the insertion order (which is similar to dict in Python 3.7+).
In [1]:
val map  = hashMapOf(1 to "x", 2 to "y", -1 to "zz")
println(map)
{-1=zz, 1=x, 2=y}
Out[1]:
null

LinkedHashMap

Notice that the order of keys is the same as their insertion order!

In [1]:
val map = linkedMapOf(
    1 to "x", 2 to "y", -1 to "zz"
)
println(map)
{1=x, 2=y, -1=zz}
In [8]:
for ((key, value) in map) {
    println("$key = $value")
}
1 = x
2 = y
-1 = zz
In [10]:
map.forEach { 
    (key, value) -> println("$key = $value") 
}
1 = x
2 = y
-1 = zz
In [13]:
val list: List<String> = map.map { 
    (key, value) -> value
}
list
Out[13]:
[x, y, zz]

Count Occurences of Elements in a Collection

In [3]:
listOf(1, 1, 3, 2, 1, 2, 4).groupingBy { it }.eachCount()
In [ ]:

Comments