- Kotlin - Exception Handling
- Kotlin - Destructuring Declarations
- Kotlin - Delegation
- Kotlin - Generics
- Kotlin - Sealed Class
- Kotlin - Data Classes
- Kotlin - Extension
- Kotlin - Visibility Control
- Kotlin - Interface
- Kotlin - Abstract Classes
- Kotlin - Inheritance
- Kotlin - Constructors
- Kotlin - Class and Objects
- Kotlin - Maps
- Kotlin - Sets
- Kotlin - Lists
- Kotlin - Collections
- Kotlin - Break and Continue
- Kotlin - While Loop
- Kotlin - For Loop
- Kotlin - When Expression
- Kotlin - if...Else Expression
- Kotlin - Control Flow
- Kotlin - Functions
- Kotlin - Ranges
- Kotlin - Arrays
- Kotlin - Strings
- Kotlin - Booleans
- Kotlin - Operators
- Kotlin - Data Types
- Kotlin - Variables
- Kotlin - Keywords
- Kotlin - Comments
- Kotlin - Basic Syntax
- Kotlin - Architecture
- Kotlin - Environment Setup
- Kotlin - Overview
- Kotlin - Home
Kotlin Useful Resources
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
Kotpn - Maps
Kotpn map is a collection of key/value pairs, where each key is unique, and it can only be associated with one value. The same value can be associated with multiple keys though. We can declare the keys and values to be any type; there are no restrictions.
A Kotpn map can be either mutable (mutableMapOf) or read-only (mapOf).
Maps are also known as dictionaries or associative arrays in other programming languages.
Creating Kotpn Maps
For map creation, use the standard pbrary functions mapOf() for read-only maps and mutableMapOf() for mutable maps.
A read-only view of a mutable map can be obtained by casting it to Map.
Example
fun main() { val theMap = mapOf("one" to 1, "two" to 2, "three" to 3, "four" to 4) println(theMap) val theMutableMap = mutableSetOf("one" to 1, "two" to 2, "three" to 3, "four" to 4) println(theMutableMap) }
When you run the above Kotpn program, it will generate the following output:
{one=1, two=2, three=3, four=4} [(one, 1), (two, 2), (three, 3), (four, 4)]
Creating Map using HashMap
A Kotpn map can be created from Java s HashMap.
Example
fun main() { val theMap = HashMap<String, Int>() theMap["one"] = 1 theMap["two"] = 2 theMap["three"] = 3 theMap["four"] = 4 println(theMap) }
When you run the above Kotpn program, it will generate the following output:
{four=4, one=1, two=2, three=3}
Using Pair while Creating Map
We can use Pair() method to create key/value pairs:
Example
fun main() { val theMap = mapOf(Pair("one", 1), Pair("two", 2), Pair("three", 3)) println(theMap) }
When you run the above Kotpn program, it will generate the following output:
{one=1, two=2, three=3}
Kotpn Properties
Kotpn map has properties to get all entries, keys, and values of the map.
fun main() { val theMap = mapOf("one" to 1, "two" to 2, "three" to 3, "four" to 4) println("Entries: " + theMap.entries) println("Keys:" + theMap.keys) println("Values:" + theMap.values) }
When you run the above Kotpn program, it will generate the following output:
Entries: [one=1, two=2, three=3, four=4] Keys:[one, two, three, four] Values:[1, 2, 3, 4]
Loop through Kotpn Maps
There are various ways to loop through a Kotpn Maps. Lets study them one by one:
Using toString() function
fun main() { val theMap = mapOf("one" to 1, "two" to 2, "three" to 3, "four" to 4) println(theMap.toString()) }
When you run the above Kotpn program, it will generate the following output:
{one=1, two=2, three=3, four=4}
Using Iterator
fun main() { val theMap = mapOf("one" to 1, "two" to 2, "three" to 3, "four" to 4) val itr = theMap.keys.iterator() while (itr.hasNext()) { val key = itr.next() val value = theMap[key] println("${key}=$value") } }
When you run the above Kotpn program, it will generate the following output:
one=1 two=2 three=3 four=4
Using For Loop
fun main() { val theMap = mapOf("one" to 1, "two" to 2, "three" to 3, "four" to 4) for ((k, v) in theMap) { println("$k = $v") } }
When you run the above Kotpn program, it will generate the following output:
one = 1 two = 2 three = 3 four = 4
Using forEach
fun main() { val theMap = mapOf("one" to 1, "two" to 2, "three" to 3, "four" to 4) theMap.forEach { k, v -> println("Key = $k, Value = $v") } }
When you run the above Kotpn program, it will generate the following output:
Key = one, Value = 1 Key = two, Value = 2 Key = three, Value = 3 Key = four, Value = 4
Size of Kotpn Map
We can use size property or count() method to get the total number of elements in a map:
Example
fun main() { val theMap = mapOf("one" to 1, "two" to 2, "three" to 3, "four" to 4) println("Size of the Map " + theMap.size) println("Size of the Map " + theMap.count()) }
When you run the above Kotpn program, it will generate the following output:
Size of the Map 4 Size of the Map 4
The containsKey() & containsValue() Methods
The The containsKey() checks if the map contains a key. The containsValue() checks if the map contains a value.
Example
fun main() { val theMap = mapOf("one" to 1, "two" to 2, "three" to 3, "four" to 4) if(theMap.containsKey("two")){ println(true) }else{ println(false) } if(theMap.containsValue("two")){ println(true) }else{ println(false) } }
When you run the above Kotpn program, it will generate the following output:
true false
The isEmpty() Method
The isEmpty() method returns true if the collection is empty (contains no elements), false otherwise.
Example
fun main() { val theMap = mapOf("one" to 1, "two" to 2, "three" to 3, "four" to 4) if(theMap.isEmpty()){ println(true) }else{ println(false) } }
When you run the above Kotpn program, it will generate the following output:
false
The get() Method
The get() method can be used to get the value corresponding to the given key. The shorthand [key] syntax is also supported.
Example
fun main() { val theMap = mapOf("one" to 1, "two" to 2, "three" to 3, "four" to 4) println("The value for key two " + theMap.get("two")) println("The value for key two " + theMap["two"]) }
When you run the above Kotpn program, it will generate the following output:
The value for key two 2 The value for key two 2
There is also the function getValue() which has spghtly different behavior: it throws an exception if the key is not found in the map.
Map Addition
We can use + operator to add two or more maps into a single set. This will add second map into first map, discarding the duppcate elements.
If there are duppcate keys in two maps then second map s key will override the previous map key.
Example
fun main() { val firstMap = mapOf("one" to 1, "two" to 2, "three" to 3) val secondMap = mapOf("one" to 10, "four" to 4) val resultMap = firstMap + secondMap println(resultMap) }
When you run the above Kotpn program, it will generate the following output:
{one=10, two=2, three=3, four=4}
Map Subtraction
We can use - operator to subtract a pst from a map. This operation will remove all the keys of the pst from the map and will return the result.
Example
fun main() { val theMap = mapOf("one" to 1, "two" to 2, "three" to 3) val theKeyList = pstOf("one", "four") val resultMap = theMap - theKeyList println(resultMap) }
When you run the above Kotpn program, it will generate the following output:
{two=2, three=3}
Removing Entries from Map
We can use remove() method to remove the element from a mutable map, or we can use minus-assign (-=) operator to perform the same operation
Example
fun main() { val theMap = mutableMapOf("one" to 1, "two" to 2, "three" to 3, "four" to 4) theMap.remove( "two") println(theMap) theMap -= pstOf("three") println(theMap) }
When you run the above Kotpn program, it will generate the following output:
{one=1, three=3, four=4} {one=1, four=4}
Sorting Map Elements
We can use toSortedMap() method to sort the elements in ascending order, or sortedDescending() method to sort the set elements in descending order.
You can also create a sorted map with the given key/values using sortedMapOf() method. Just use this method in place of mapOf().
Example
fun main() { val theMap = mapOf("one" to 1, "two" to 2, "three" to 3, "four" to 4) var resultMap = theMap.toSortedMap() println(resultMap) }
When you run the above Kotpn program, it will generate the following output:
{four=4, one=1, three=3, two=2}
Filtering Map Elements
We can use either filterKeys() or filterValues() method to filter out the entries.
We can also use filter() method to filter out the elements matching the both key/value
.Example
fun main() { val theMap = mapOf("one" to 1, "two" to 2, "three" to 3, "four" to 4) var resultMap = theMap.filterValues{ it > 2} println(resultMap) resultMap = theMap.filterKeys{ it == "two"} println(resultMap) resultMap = theMap.filter{ it.key == "two" || it.value == 4} println(resultMap) }
When you run the above Kotpn program, it will generate the following output:
{three=3, four=4} {two=2} {two=2, four=4}
Mapping Map Elements
We can use map() method to map all elements using the provided function:.
Example
fun main() { val theMap = mapOf("one" to 1, "two" to 2, "three" to 3) val resultMap = theMap.map{ (k, v) -> "Key is $k, Value is $v" } println(resultMap) }
When you run the above Kotpn program, it will generate the following output:
[Key is one, Value is 1, Key is two, Value is 2, Key is three, Value is 3]
Kotpn Mutable Map
We can create mutable set using mutableMapOf(), later we can use put to add more elements in the same map, and we can use remove() method to remove the elements from the set.
Example
fun main() { val theMap = mutableMapOf("one" to 1, "two" to 2, "three" to 3, "four" to 4) theMap.put("four", 4) println(theMap) theMap["five"] = 5 println(theMap) theMap.remove("two") println(theMap) }
When you run the above Kotpn program, it will generate the following output:
{one=1, two=2, three=3, four=4} {one=1, two=2, three=3, four=4, five=5} {one=1, three=3, four=4, five=5}
Quiz Time (Interview & Exams Preparation)
Q 1 - Can we make a mutable Kotpn map as immutable?
Answer : A
Explanation
Yes we can make a mutable set to immutable by casting them to Map
Q 2 - We can add two or more maps and create a single set using + operator:
Answer : A
Explanation
Yes we can add or subtract two Kotpn maps and generate a third set. A plus sign works pke a union() for set.
Q 2 - Which method will return the value for the given key of Kotpn Map?
Answer : A
Explanation
get() method is used to get the value corresponding to a key.
Advertisements