Before we switch what Kotlin has to offer us in terms of Map Interface. Let us first recap the Map Interface with the java.
The map interface is present in java.util package which presents a mapping between the Key, Value.
A typical Java program for the Map Interface goes like this:
// Java program to demonstrate // the working of Map interface import java.util.*; class HashMapDemo { public static void main(String args[]) { Map<String, Integer> hm = new HashMap<String, Integer>(); hm.put("a", new Integer(111)); hm.put("b", new Integer(222)); hm.put("c", new Integer(333)); hm.put("d", new Integer(444)); // Traversing through the map for (Map.Entry<String, Integer> me : hm.entrySet()) { System.out.print(me.getKey() + ":"); System.out.println(me.getValue()); } } }
The output of the above code will be:
a:111
b:222
c:333
d:444
Kotlin Map Interface
Kotlin Map is an interface and is the generic collection of all the elements. It also stores the data in the form of (K,V) key and Value pair. The key in the (K,V) stands for the key is unique and can only hold one value for each key. The key and value may be in the different pairs such as:
<Int,Int>
<Int,String>
<Char,String>
Map interface is immutable in nature, have a fixed size and the methods available in the Kotlin Map Interface supports only the read only access.
If we want to use the Map interface in the Kotlin than we have to use the function called mapOf() or we can use mapOf(k,v)>().
Declaration:
interfaceMap<K,V> (source)
Code:
fun main(args: Array<String>){ val myMap = mapOf<Int,String>(1 to "Ishank", 4 to "Aditya", 3 to "Yugansh") for(key in myMap.keys){ println(myMap[key]) } }
Output:
Ishank
Aditya
Yugansh
Generic Example
fun main(args: Array<String>){ val myMap: Map<Int, String> = mapOf<Int,String>(1 to "Ishank", 4 to "Aditya", 3 to "Yugansh") for(key in myMap.keys){ println("Element at key $key = ${myMap.get(key)}") } }
Output:
Element at key 1 = Ishank
Element at key 4 = Aditya
Element at key 3 = Yugansh
Non-Generic Example
If we do not specify the types of (K,V) than it can take different types of key and value. This happens because all the class uses <Any,Any> types. For Example:
fun main(args: Array<String>){ val myMap = mapOf(1 to "Ishank", 4 to "Aditya", 3 to "Yugansh","Deepansh" to "Deepansh", "two" to 2) for(key in myMap.keys){ println("Element at key $key = ${myMap.get(key)}") } }
Output:
Element at key 1 = Ishank
Element at key 4 = Aditya
Element at key 3 = Yugansh
Element at key Deepansh = Deepansh
Element at key two = 2
I hope you got an idea of how to use map in kotlin. Comment down below if you have any queries.