kotlin-hashmap-complete-reference-feature-image

Kotlin/Android HashMap tutorial with examples

In this tutorial, we’ll show you many Kotlin HashMap methods and functions that also work on Android. You will see many examples to:

  • Create, initialize, add item, get value, update, remove entries in a HashMap
  • Iterate over a HashMap
  • Filter a HashMap
  • Convert HashMap to List, transform a HashMap keys or values

Related Posts:
Kotlin List & Mutable List
Kotlin Queue


Key points to note about Kotlin HashMap

  • A HashMap is a collection of key-value pairs that maps each key to exactly one value.
  • HashMap is unordered. The key-value pair coming later could be ordered first.
  • We can add an entry with null value or null key to Kotlin HashMap

Create a new HashMap

We can create a new HashMap using constructor.
If you want to create a new HashMap that allows null values and null keys, just use the question mark ? right after the types.

var hashMap: HashMap<String, Int> = HashMap<String, Int>()
var nullableHashMap: HashMap<String?, Int?> = HashMap<String?, Int?>()

Initialize a HashMap with values

The example show you way to initialize a HashMap using hashMapOf() function:

var bzkMap: HashMap<String, Int> = hashMapOf("zero" to 0, "onek" to 1000, "twok" to 2000, "bezkoder" to 9999)
println(bzkMap)

Output:

{zero=0, onek=1000, twok=2000, bezkoder=9999}

Add item to HashMap

We can add an item (key-value pair) to a Kotlin HashMap using:

  • square brackets [] operator
  • put() method
var bzkMap: HashMap<String, Int> = HashMap<String, Int>()
bzkMap.put("bezkoder", 9999)
println("After put: " + bzkMap)

bzkMap["zero"] = 0
println("After []: " + bzkMap)

Output:

After put: {bezkoder=9999}
After []: {zero=0, bezkoder=9999}

You can also add all key/value pairs of another Map to current Map using putAll() method.

bzkMap.putAll(mapOf("onek" to 1000, "twok" to 2000))
println("After putAll: " + bzkMap)

Output:

After put: {bezkoder=9999}
After putAll: {zero=0, onek=1000, bezkoder=9999, twok=2000}

Kotlin HashMap get

The examples show you way to get value by key using:

  • square brackets [] operator
  • get() method
  • getOrElse() method that returns default value if there is no value for the key
  • getOrPut() method that returns default value if there is no value for the key, and put the entry with key and default value to the HashMap
var bzkMap: HashMap<String, Int> = hashMapOf("onek" to 1000, "twok" to 2000, "bezkoder" to 9999)

bzkMap.get("bezkoder")
// 9999

bzkMap["bezkoder"]
// 9999

bzkMap.getOrElse("zkoder") { 123 }
// 123
// bzkMap: {onek=1000, twok=2000, bezkoder=9999}

bzkMap.getOrPut("zkoder") { 123 }
// 123
// bzkMap: {onek=1000, twok=2000, bezkoder=9999, zkoder=123}

We can get all keys or values with keys & values property.

bzkMap.keys
// [onek, twok, bezkoder, zkoder]

bzkMap.values
// [1000, 2000, 9999, 123]

Kotlin HashMap get key by value

We can find all keys that are paired with a given value using filterValues() method and Map’s keys property.
For example, there are 2 entries with value = 9999 in the HashMap:

  • {“zkoder”, 9999}
  • {“bezkoder”, 9999}
var bzkMap: HashMap<String, Int> = hashMapOf("zkoder" to 9999, "year" to 2020, "bezkoder" to 9999)

val keys = bzkMap.filterValues { it == 9999 }.keys
println(keys)

Output:

[zkoder, bezkoder]

Kotlin HashMap update values

We can update values in HashMap by given existing keys using replace(), put() or square brackets [].

var bzkMap: HashMap<String, Int> = hashMapOf("onek" to 1000, "twok" to 2000, "bezkoder" to 9999)

bzkMap.replace("bezkoder", 8888)
println(bzkMap)

bzkMap.put("bezkoder", 2020)
println(bzkMap)

bzkMap["bezkoder"] = 9999
println(bzkMap)

Output:

{onek=1000, twok=2000, bezkoder=8888}
{onek=1000, twok=2000, bezkoder=2020}
{onek=1000, twok=2000, bezkoder=9999}

Check HashMap empty and size

You can:

var bzkMap: HashMap<String, Int> = hashMapOf("onek" to 1000, "twok" to 2000, "bezkoder" to 9999)
println(bzkMap.size)
println(bzkMap.isEmpty())
println(bzkMap.isNotEmpty())

Output:

3
false
true

Check HashMap contains key/value

We can check existence of:

var bzkMap: HashMap<String, Int> = hashMapOf("onek" to 1000, "twok" to 2000, "bezkoder" to 9999)

bzkMap.containsKey("bezkoder") // true
bzkMap.containsKey("zkoder")   // false

bzkMap.containsValue(1234)     // false
bzkMap.containsValue(1000)     // true

Kotlin HashMap remove

The examples show you how to:

  • remove element (entry) by key using remove() method or .keys.remove() method
  • removes the first entry with the given value using .values.remove() method
  • remove all entries from a HashMap using clear() method
var bzkMap: HashMap<Int, String> =
  hashMapOf(0 to "zero", 1 to "one", 2 to "two", 3 to "three", 4 to "four", 5 to "five")
bzkMap.remove(1)
println(bzkMap)

bzkMap.keys.remove(4)
println(bzkMap)

bzkMap.values.remove("zero")
println(bzkMap)
 
bzkMap.clear()
println(bzkMap)

Output:

{0=zero, 2=two, 3=three, 4=four, 5=five}
{0=zero, 2=two, 3=three, 5=five}
{2=two, 3=three, 5=five}
{}

Iterate over a HashMap in Kotlin

The examples show you how to iterate over a Kotlin HashMap using:

var bzkMap: HashMap<Int, String> = hashMapOf(0 to "zero", 1 to "one", 2 to "two", 3 to "three")

bzkMap.forEach { (key, value) -> println("$key = $value") }

for ((key, value) in bzkMap) {
  println("$key = $value")
}

Output:

0 = zero
1 = one
2 = two
3 = three

Kotlin HashMap filter

The examples show you how to filter a HashMap using:

var bzkMap: HashMap<String, Int> = hashMapOf("zero" to 0, "onek" to 1000, "twok" to 2000, "bezkoder" to 9999)

val filter1 = bzkMap.filterKeys { it.length < 5 }
println(filter1)
// {zero=0, onek=1000, twok=2000}

val filter2 = bzkMap.filterValues { it > 500 }
println(filter2)
// {onek=1000, twok=2000, bezkoder=9999}

val filter3 = bzkMap.filter { (key, value) -> key.length < 5 && value > 500 }
println(filter3)
// {onek=1000, twok=2000}

Kotlin HashMap to List

We can easily transform a Kotlin Map to List using map() method. It will return a new List with elements transformed from entries in original Map.

var bzkMap: HashMap<Int, String> = hashMapOf(0 to "zero", 1 to "one", 2 to "two", 3 to "three")

var bzkList = bzkMap.map { it.key.toString() + '-' + it.value }
println(bzkList)

Output:

[0-zero, 1-one, 2-two, 3-three]

Sometimes the transformation could produce null, so we filter out the nulls by using the mapNotNull() function instead of map()

var bzkList = bzkMap.mapNotNull { if (it.key == 0) null else it.key.toString() + '-' + it.value }
println(bzkList)

Output:

[1-one, 2-two, 3-three]

You can also use mapTo() and mapNotNullTo() with a destination as input pamameter.

var bzkList = mutableListOf<String>()

bzkMap.mapTo(bzkList) { it.key.toString() + '-' + it.value }
println(bzkList)

bzkList.clear()

bzkMap.mapNotNullTo(bzkList) { if (it.key == 0) null else it.key.toString() + '-' + it.value }
println(bzkList)

Output:

[0-zero, 1-one, 2-two, 3-three]
[1-one, 2-two, 3-three]

Kotlin transform HashMap keys

The example shows you how to transform HashMap keys in Kotlin using:

var bzkMap: HashMap<Int, String> = hashMapOf(0 to "zero", 1 to "one", 2 to "two", 3 to "three")

var keysMap = bzkMap.mapKeys { it.key * 100 }
println(keysMap)

var newKeysMap = mutableMapOf<Int, String>()

bzkMap.mapKeysTo(newKeysMap) { it.key * 1000 }
println(newKeysMap)

Output:

{0=zero, 100=one, 200=two, 300=three}
{0=zero, 1000=one, 2000=two, 3000=three}

Kotlin transform HashMap values

The example shows you how to transform HashMap values in Kotlin using:

var bzkMap: HashMap<Int, String> = hashMapOf(0 to "zero", 1 to "one", 2 to "two", 3 to "three")

var valuesMap = bzkMap.mapValues { it.value.toUpperCase() }
println(valuesMap)

var newValuesMap = mutableMapOf<Int, String>()

bzkMap.mapValuesTo(newValuesMap) { '-' + it.value.toUpperCase() + '-' }
println(newValuesMap)

Output:

{0=ZERO, 1=ONE, 2=TWO, 3=THREE}
{0=-ZERO-, 1=-ONE-, 2=-TWO-, 3=-THREE-}

Kotlin Hashmap with different value types

To create a HashMap that can contain different value types, we use Any which is the supertype of all the other types.

val bzkMap = HashMap<String, Any>()
bzkMap.put("site", "bezkoder.com")
bzkMap.put("start", 2019)
bzkMap.put("working", true)

println(bzkMap)

Output:

{site=bezkoder.com, start=2019, working=true}

Conclusion

In this Kotlin tutorial, we’ve learned some important points of HashMap. Now you can create, initialize a HashMap, add, update and remove items from a HashMap. You also know way to iterate over a HashMap, filter or transform a HashMap.

Happy learning! See you again!

Further Reading

Leave a Reply

Your email address will not be published. Required fields are marked *