map-collection-kotlin

Map in Kotlin

Maps are not part of collection but built based on the collection concepts in kotlin, but map is built using collections like Set is used for keys and List is used for value

Map is nothing but a key value pair mappings, every in the map a has a value and every value has a key.

Map keys follows Set interface and allows only unique values, Map Values are following List interface and allows duplicates

It is similar to the attendance system, the roll number is Keys, and names are Values. Roll Number is unique but the names could be duplicates.

Maps provides three collection views/retrievals for user :

  • The set of keys
  • the list of Values
  • the set of key value mapping
There are different types of maps in kotlin:
  • HashMap
  • LinkedHashMap
  • TreeMap

Map creation in Kotlin

You can create maps in kotlin using the mapOf() function, mapsOf() function accepts variable number of arguments as key-value pairs.

Keyword to is used to map the keys with value in maps of kotlin. fun main(args: Array<String>) { var abc = mapOf(1 to 1, 2 to "two", 3 to "tres") println(abc[2]) }

Manipulate Collections

Methods present in the Map in Kotlin

[ ]

[ ] operator fetches the valu at the given index, please aware it brig the value not the key. fun main(args: Array<String>) { var abc = mapOf(1 to 1, 2 to "two", 3 to "tres") println(abc[2]) }

entries

enries prperty in Map returns a read-only [Set] of all key/value pairs in this map. fun main(args: Array<String>) { var abc = mapOf(1 to 1, 2 to "two", 3 to "tres") println(abc.entries) }

get()

get() function returns the value corresponding to the given [key], or 'null' if such a key is not present in the map. fun main(args: Array<String>) { var abc = mapOf("a" to 1, "b" to "two", "c" to "tres") println(abc.get("b")) println(abc.get("xyz")) }

size

size property returns the number of key/value pairs in the map, key-pair will be considered as one element. fun main(args: Array<String>) { var abc = mapOf("a" to 1, "b" to "two", "c" to "tres") println(abc.size) }

keys

keys property returns a read-only Set of all keys in this map. fun main(args: Array<String>) { var abc = mapOf("a" to 1, "b" to "two", "c" to "tres") println(abc.keys) }

values

values property in map returns a read-only List of all values in this map. Note that this collection may contain duplicate values. fun main(args: Array<String>) { var abc = mapOf("a" to 1, "b" to "two", "c" to "tres") println(abc.values) }

Set Collections in Kotlin

getValue()

getValue() function returns the value for the given key or throws an exception if there is no such key in the map.

NoSuchElementException when the map doesn't contain a value for the specified key and no implicit default value was provided for that map. fun main(args: Array<String>) { var abc = mapOf("a" to 1, "b" to "two", "c" to "tres") println(abc.getValue("c")) }

containsKey

conainsKey() function returns 'true' if the map contains the specified key otherwise false fun main(args: Array<String>) { var abc = mapOf("a" to 1, "b" to "two", "c" to "tres") println(abc.containsKey("c")) }

containsValue()

containsValue() function returns 'true' if the map maps one or more keys to the specified value otherwise false fun main(args: Array<String>) { var abc = mapOf("a" to 1, "b" to "two", "c" to "tres") println(abc.containsValue("tres")) }

getOrDefault()

getOrDefault() returns the value corresponding to the given key, or defaultValue if such a key is not present in the kotlin map.

You have to set the lambda to return default value fun main(args: Array<String>) { var abc = mapOf("a" to 1, "b" to "two", "c" to "tres") println(abc.getOrDefault("b", {"someDefaultValue"})) }

isEmpty()

isEmpty() function returns 'true' if the map is empty (contains no elements), 'false' otherwise. fun main(args: Array<String>) { var abc = mapOf("a" to 1, "b" to "two", "c" to "tres") println(abc.isEmpty()) }

List Collections in Kotlin

getOrElse()

getOrElse() function returns the value for the given key, or the result of the defaultValue function if there was no entry for the given key.

Default Value must be in the form of lambda fun main(args: Array<String>) { var abc = mapOf("a" to 1, "b" to "two", "c" to "tres") println(abc.getOrElse("a", {"I am kidding"})) println(abc.getOrElse("abbbb", {"I am kidding"})) }

any()

any() function return true if there is at least one key-value pair fun main(args: Array<String>) { var abc = mapOf("a" to 1, "b" to "two", "c" to "tres") println(abc.any()) }

count()

count() function returns the number of entries in this map fun main(args: Array<String>) { var abc = mapOf("a" to 1, "b" to "two", "c" to "tres") println(abc.count()) }

none

none() function returns `true` if the map has no entries fun main(args: Array<String>) { var abc = mapOf("a" to 1, "b" to "two", "c" to "tres") println(abc.none()) }

orEmpty()

orEmpty() function returns the Map if its not `null`, or the empty Map otherwise. fun main(args: Array<String>) { var abc = mapOf("a" to 1, "b" to "two", "c" to "tres") println(abc.orEmpty()) }

plus()

Creates a new read-only map by replacing or adding an entry to this map from a given key-value pair, basically return new map but it will not alter the original map as it is immutable. fun main(args: Array<String>) { var abc = mapOf("a" to 1, "b" to "two", "c" to "tres") var newAbc = abc.plus("g" to "seven") println(newAbc) println(abc) }

minus()

minus() function returns a map containing all entries of the original map except the entry with the given key. fun main(args: Array<String>) { var abc = mapOf("a" to 1, "b" to "two", "c" to "tres") var newAbc = abc.minus("b") println(newAbc) println(abc) }

toList()

toList() function returns a List containing all key-value pairs. fun main(args: Array<String>) { var abc = mapOf("a" to 1, "b" to "two", "c" to "tres") var newAbc = abc.toList() println(newAbc) println(abc) }

Collections

isNotEmpty()

isNotEmpty() function returns `true` if this map is not empty. fun main(args: Array<String>) { var abc = mapOf("a" to 1, "b" to "two", "c" to "tres") println(abc.isNotEmpty()) }

toSortedMap()

Converts this Map to a SortedMap so iteration order will be in key order. fun main(args: Array<String>) { var abc = mapOf("b" to "two", "c" to "tres", "a" to 1) println(abc.toSortedMap()) }

Traversing the Maps

Enhanced For Loop :

You can use the enhanced for loop to to navigate through the kotlin map.

fun main(args: Array<String>) { var sampleMap = mapOf("b" to "two", "c" to "tres", "a" to 1) for ((key, value) in sampleMap) { println("the key is $key and the respective value is $value") } }

For Each Lambda :

We can use the ordinary for each loop to traverse the Map fun main(args: Array<String>) { var sampleMap = mapOf("b" to "two", "c" to "tres", "a" to "1") sampleMap.forEach { key, value -> println("$key = $value") } }

For Each Loop:

We can use normal for each loop, and we can access the elements using it keyword. fun main(args: Array<String>) { var sampleMap = mapOf("b" to "two", "c" to "tres", "a" to "1") sampleMap.forEach { println("${it.key} = ${it.value}") } }

aaaaaaaaaaaaa
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions
Copyright © CherCher Tech