Left Index

Kotlin mapOf() Function

In Kotlin, map is a collection containing data in pairs, which consists of key and value, and key are always unique and one key hold one value only. mapOf() create Immutable(i.e. read only) maps and mutablemapof() create Mutable(i.e. can be modify) maps. Let's create example of mapOf():

Example:
package com.theitbulls.kotlinex

import java.util.ArrayList

fun main(args: Array<String>) {
	var mapOf = mapOf<Int, String>(1 to "John", 2 to "Tony", 3 to "Denial")
	var keys = mapOf.keys
	for(key in keys) {
		println("Key: ${key}, Value: ${mapOf.get(key)}")
	}
}
Output:
Key: 1, Value: John
Key: 2, Value: Tony
Key: 3, Value: Denial

Map keys, values and entries
package com.theitbulls.kotlinex

import java.util.ArrayList

fun main(args: Array<String>) {
	var mapOf = mapOf<Int, String>(1 to "John", 2 to "Tony", 3 to "Denial")
	
	println("Entries: ${mapOf.entries}")
	println("Keys: ${mapOf.keys}")
	println("Values: ${mapOf.values}")
}
Output:
Entries: [1=John, 2=Tony, 3=Denial]
Keys: [1, 2, 3]
Values: [John, Tony, Denial]

Iterate Kotlin Map
package com.theitbulls.kotlinex

import java.util.ArrayList

fun main(args: Array<String>) {
	var mapOf = mapOf<Int, String>(1 to "John", 2 to "Tony", 3 to "Denial")

	// iterate map using keys set	
	var keys = mapOf.keys
	for(key in keys) {
		println("Key: ${key}, Value: ${mapOf.get(key)}")
	}
	
	println()
	// iterate map using for loop
	for(map in mapOf) {
		println("Key: ${map.key}, Value: ${map.value}")
	}
	
	println()
	// using forEach
	mapOf.forEach { item -> println("Key: ${item.key}, Value: ${item.value}") }
}
Output:
Key: 1, Value: John
Key: 2, Value: Tony
Key: 3, Value: Denial

Key: 1, Value: John
Key: 2, Value: Tony
Key: 3, Value: Denial

Key: 1, Value: John
Key: 2, Value: Tony
Key: 3, Value: Denial

Getting value of mapOf()
package com.theitbulls.kotlinex

import java.util.ArrayList

fun main(args: Array<String>) {
	println("Value for key(3): ${mapOf.get(3)}")
	println("Value for key(4): ${mapOf.getOrDefault(4, "Not found for key 4")}")
	println("Value for key(2): ${mapOf.getOrElse(2) {"Not found for key 2"}}")
	println("Value for key(3): ${mapOf.getValue(3)}")
}
Output:
Value for key(3): Denial
Value for key(4): Not found for key 4
Value for key(2): Tony
Value for key(3): Denial