Val theMap = mapOf("one" to 1, "two" to 2, "three" to 3) This operation will remove all the keys of the list from the map and will return the result. We can use - operator to subtract a list from a map. Val secondMap = mapOf("one" to 10, "four" to 4) Val firstMap = mapOf("one" to 1, "two" to 2, "three" to 3) If there are duplicate keys in two maps then second map's key will override the previous map key. This will add second map into first map, discarding the duplicate elements. We can use + operator to add two or more maps into a single set. There is also the function getValue() which has slightly different behavior: it throws an exception if the key is not found in the map. Println("The value for key two " + theMap) Println("The value for key two " + theMap.get("two")) The get() method can be used to get the value corresponding to the given key. The isEmpty() method returns true if the collection is empty (contains no elements), false otherwise. The containsValue() checks if the map contains a value. The The containsKey() checks if the map contains a key. The containsKey() & containsValue() Methods Println("Size of the Map " + theMap.size) We can use size property or count() method to get the total number of elements in a map: Example Lets study them one by one: Using toString() function There are various ways to loop through a Kotlin Maps. Kotlin map has properties to get all entries, keys, and values of the map. We can use Pair() method to create key/value pairs: Example When you run the above Kotlin program, it will generate the following output:Ī Kotlin map can be created from Java's HashMap. Val theMutableMap = mutableSetOf("one" to 1, "two" to 2, "three" to 3, "four" to 4) Val theMap = mapOf("one" to 1, "two" to 2, "three" to 3, "four" to 4) A read-only view of a mutable map can be obtained by casting it to Map. Creating Kotlin Mapsįor map creation, use the standard library functions mapOf() for read-only maps and mutableMapOf() for mutable maps. Maps are also known as dictionaries or associative arrays in other programming languages. We can declare the keys and values to be any type there are no restrictions.Ī Kotlin map can be either mutable ( mutableMapOf) or read-only ( mapOf). The same value can be associated with multiple keys though. Kotlin map is a collection of key/value pairs, where each key is unique, and it can only be associated with one value.
0 Comments
Leave a Reply. |