Kotlin HashMap
$count++; if($count == 1) { include "../mobilemenu.php"; } if ($count == 2) { include "../sharemediasubfolder.php"; } ?>
A HashMap in Kotlin implements a key value pair dictionary.
You can query the HashMap with a key, and get the value stored in it. A HashMap is unsynchronized. It permits null as a key. HashMap is mutable, meaning we are able to modify the Map once it is created.
Initializing a HashMap in Kotlin
In the following example, we are creating a HashMap of alphabets. We used the helper function hashMapOf.
package com.cosmiclearn.kotlin.hashmap
fun main(args: Array<String>)
{
val alphabetMap = hashMapOf("A" to "Apple", "B" to "Ball",
"C" to "Cat")
println(alphabetMap)
}
Output:
{A=Apple, B=Ball, C=Cat}
Process finished with exit code 0
We can iterate a HashMap using for each loop. In the following example, we are iterating through the HashMap of alphabets and printing each key and value for the alphabet.
package com.cosmiclearn.kotlin.hashmap
fun main(args: Array<String>)
{
val alphabetMap = hashMapOf("A" to "Apple", "B" to "Ball",
"C" to "Cat")
for((alphabet,word) in alphabetMap)
{
println(alphabet + " for " + word)
}
}
Output:
A for Apple
B for Ball
C for Cat
Process finished with exit code 0
Instead of using indexing operator [ ], we can use get method to get value for given key. In the following example, we used the get function to get the value of the planet at the given index as key.
package com.cosmiclearn.kotlin.hashmap
fun main(args: Array<String>)
{
var planets = hashMapOf<Int, String>( 1 to "Earth", 2 to "Mars", 3 to "Jupiter")
for(key in planets.keys)
{
println(key.toString() + " = " + planets.get(key))
}
}
Output:
1 = Earth
2 = Mars
3 = Jupiter
Process finished with exit code 0
We can use getOrDefault method to get value for given key, and to return a default value, if the key is not present. In the following example, we used the getOrDefault function to get the value of the planet, which does not exist.
package com.cosmiclearn.kotlin.hashmap
fun main(args: Array<String>)
{
var planets = hashMapOf<Int, String>( 1 to "Earth", 2 to "Mars", 3 to "Jupiter")
println("Four = " + planets.getOrDefault(4, "Alien Planet"))
}
Output:
Four = Alien Planet
Process finished with exit code 0
In the following example, we created a HashMap. We can use put method, that takes a key and value as parameters. In the following example, we used the put method to insert Planets into our HashMap.
package com.cosmiclearn.kotlin.hashmap
fun main(args: Array<String>)
{
var planets = HashMap<Int, String>()
planets.put(1, "Earth");
planets.put(2, "Mars");
planets.put(3, "Pluto")
for(key in planets.keys)
{
println(key.toString() + " = " + planets.get(key))
}
}
Output:
1 = Earth
2 = Mars
3 = Pluto
Process finished with exit code 0
Let us say we want to replace an element in the HashMap. We can use the put method to replace an existing element in the HashMap. In the following example, we used put method to replace Mars with Jupiter.
package com.cosmiclearn.kotlin.hashmap
fun main(args: Array<String>)
{
var planets = HashMap<Int, String>()
planets.put(1, "Earth");
planets.put(2, "Mars");
planets.put(3, "Pluto")
println("First map = ")
for(key in planets.keys)
{
println(key.toString() + " = " + planets.get(key))
}
planets.put(2, "Jupiter")
println("\nAfter replacing = ")
for(key in planets.keys)
{
println(key.toString() + " = " + planets.get(key))
}
}
Output:
First map =
1 = Earth
2 = Mars
3 = Pluto
After replacing =
1 = Earth
2 = Jupiter
3 = Pluto
Process finished with exit code 0
Instead of put function, we can also use replace function to replace value in the HashMap. In the following example, we used replace method to replace the value in the HashMap.
package com.cosmiclearn.kotlin.hashmap
fun main(args: Array<String>)
{
var planets = HashMap<Int, String>()
planets.put(1, "Earth");
planets.put(2, "Mars");
planets.put(3, "Pluto")
println("First map = ")
for(key in planets.keys)
{
println(key.toString() + " = " + planets.get(key))
}
planets.replace(2, "Jupiter")
println("\nAfter replacing = ")
for(key in planets.keys)
{
println(key.toString() + " = " + planets.get(key))
}
}
Output:
First map =
1 = Earth
2 = Mars
3 = Pluto
After replacing =
1 = Earth
2 = Jupiter
3 = Pluto
Process finished with exit code 0
In the following example, we created a HashMap. We can use putIfAbsent method, to only insert the value if the key is absent. putIfAbsent function takes a key and value as parameters. In the following example, we used the putIfAbsent method to insert new Planets into our HashMap.
package com.cosmiclearn.kotlin.hashmap
fun main(args: Array<String>)
{
var planets = HashMap<Int, String>()
planets[1] = "Earth"
planets[2] = "Mars"
planets[3] = "Pluto"
planets.putIfAbsent(3, "Bluto")
planets.putIfAbsent(4, "Saturn")
for(key in planets.keys)
{
println(key.toString() + " = " + planets[key])
}
}
Output:
1 = Earth
2 = Mars
3 = Pluto
4 = Saturn
Process finished with exit code 0
Instead of creating a HashMap and then populating it, Kotlin provides an inbuilt hashMapOf, which can be used to create a HashMap and assign entries to the HashMap. In the following example, we used hashMapOf to create a HashMap of planets.
package com.cosmiclearn.kotlin.hashmap
fun main(args: Array<String>)
{
var planets = hashMapOf<Int, String>(1 to "Earth", 2 to "Mars", 3 to "Pluto")
println("First map = ")
for(key in planets.keys)
{
println(key.toString() + " = " + planets.get(key))
}
planets.replace(2, "Jupiter")
println("\nAfter replacing = ")
for(key in planets.keys)
{
println(key.toString() + " = " + planets.get(key))
}
}
Output:
First map =
1 = Earth
2 = Mars
3 = Pluto
After replacing =
1 = Earth
2 = Jupiter
3 = Pluto
Process finished with exit code 0
We can remove an entry from the HashMap using remove function. In the following example, we used remove function to remove the Mars from planet hashmap.
package com.cosmiclearn.kotlin.hashmap
fun main(args: Array<String>)
{
var planets = HashMap<Int, String>()
planets.put(1, "Earth");
planets.put(2, "Mars");
planets.put(3, "Pluto")
println("First map = ")
for(key in planets.keys)
{
println(key.toString() + " = " + planets.get(key))
}
planets.remove(2)
println("\nAfter removing = ")
for(key in planets.keys)
{
println(key.toString() + " = " + planets.get(key))
}
}
Output:
First map =
1 = Earth
2 = Mars
3 = Pluto
After removing =
1 = Earth
3 = Pluto
Process finished with exit code 0
We can print keys for the HashMap using keys property. In the following example, we used keys property to get the keys and we iterated through the keys and print them.
package com.cosmiclearn.kotlin.hashmap
fun main(args: Array<String>)
{
var planets = HashMap<String, String>()
planets.put("Earth", "Blue marble. Has Water. Brimming with life!");
planets.put("Mars", "Red Planet. Barren. Has no life.");
planets.put("Pluto", "It is not a Planet. It is actually a space station for Aliens.")
var planetsKey = planets.keys
for(key in planetsKey)
{
println("Planet = " + key)
}
}
Output:
Planet = Earth
Planet = Mars
Planet = Pluto
Process finished with exit code 0
We can print values for the HashMap using values function. In the following example, we used values function to get the values and we iterated through the values and print them.
package com.cosmiclearn.kotlin.hashmap
fun main(args: Array<String>)
{
var planets = HashMap<String, String>()
planets.put("Earth", "Blue marble. Has Water. Brimming with life!");
planets.put("Mars", "Red Planet. Barren. Has no life.");
planets.put("Pluto", "It is not a Planet. It is actually a space station for Aliens.")
var planetsValues = planets.values
for(value in planetsValues)
{
println("Planet Description = " + value)
}
}
Output:
Planet Description = Blue marble. Has Water. Brimming with life!
Planet Description = Red Planet. Barren. Has no life.
Planet Description = It is not a Planet. It is actually a space station for Aliens.
Process finished with exit code 0
We can check if key is present in HashMap using containsKey function. In the following example, we used containsKey function to check if the Planet is present in the HashMap.
package com.cosmiclearn.kotlin.hashmap
fun main(args: Array<String>)
{
var planets = HashMap<String, String>()
planets.put("Earth", "Blue marble. Has Water. Brimming with life!");
planets.put("Mars", "Red Planet. Barren. Has no life.");
planets.put("Pluto", "It is not a Planet. It is actually a space station for Aliens.")
if(planets.containsKey("Pluto")) {
println("Pluto is a planet!")
println("Pluto Description " + planets["Pluto"])
}
else {
println("Pluto is NOT a Planet!")
}
if(planets.containsKey("Zupiter")) {
println("Zupiter is a planet!")
println("Zupiter Description " + planets["Zupiter"])
}
else {
println("Zupiter is NOT a Planet!")
}
}
Output:
Pluto is a planet!
Pluto Description It is not a Planet. It is actually a space station for Aliens.
Zupiter is NOT a Planet!
Process finished with exit code 0
We can check if value is present in HashMap using containsValue function. In the following example, we used containsValue function to check if the Planet is present in the HashMap.
package com.cosmiclearn.kotlin.hashmap
fun main(args: Array<String>)
{
var planets = HashMap<String, String>()
planets["Earth"] = "Blue marble. Has Water. Brimming with life!";
planets["Mars"] = "Red Planet. Barren. Has no life.";
planets["Pluto"] = "It is not a Planet. It is actually a space station for Aliens."
if(planets.containsValue("Blue marble. Has Water. Brimming with life!")) {
println("Earth is present in this Solar System!")
}
else {
println("Earth is not present in this Solar System!")
}
if(planets.containsValue("Red Planet. Barren. Has no life.")) {
println("Mars is present in this Solar System!")
}
else {
println("Mars is not present in this Solar System!")
}
}
Output:
Earth is present in this Solar System!
Mars is present in this Solar System!
Process finished with exit code 0
We can find the count of the number of elements using the size function. In the following example, we used size function to get the count of number of elements in the HashMap.
package com.cosmiclearn.kotlin.hashmap
fun main(args: Array<String>)
{
var planets = HashMap<String, String>()
planets.put("Earth", "Blue marble. Has Water. Brimming with life!");
planets.put("Mars", "Red Planet. Barren. Has no life.");
planets.put("Pluto", "It is not a Planet. It is actually a space station for Aliens.")
var sizeOfHashMap = planets.size
println("Size of HashMap is $sizeOfHashMap")
}
Output:
Size of HashMap is 3
Process finished with exit code 0
We can clear all entries from HashMap using clear function. In the following example, we used clear function to remove all the entries from planet hashmap.
package com.cosmiclearn.kotlin.hashmap
fun main(args: Array<String>)
{
var planets = HashMap<String, String>()
planets.put("Earth", "Blue marble. Has Water. Brimming with life!");
planets.put("Mars", "Red Planet. Barren. Has no life.");
planets.put("Pluto", "It is not a Planet. It is actually a space station for Aliens.")
planets.clear()
var sizeOfHashMap = planets.size
println("Size of HashMap is $sizeOfHashMap")
}
Output:
Size of HashMap is 0
Process finished with exit code 0