Kotlin Tutoial

Basics

Control Flow

Array & String

Functions

Collections

OOPs Concept

Exception Handling

Null Safety

Regex & Ranges

Java Interoperability

Miscellaneous

Android

Kotlin Hashmap

In Kotlin, HashMap is a part of the Kotlin Collections framework. It is a mutable collection of key-value pairs, where each key maps to exactly one value. The keys in a HashMap are unique, and the map provides constant-time performance for basic operations like get and put, assuming the hash function disperses the elements properly among the buckets.

Here's a tutorial on how to use HashMap in Kotlin:

1. Initializing a HashMap:

val map1: HashMap<Int, String> = HashMap()  // Empty HashMap
val map2 = hashMapOf(1 to "A", 2 to "B", 3 to "C")

2. Adding Elements:

val animals = HashMap<String, String>()
animals["Bird"] = "Parrot"
animals["Mammal"] = "Lion"

3. Accessing Values:

Using the key, you can retrieve the corresponding value from the map:

val bird = animals["Bird"]  // bird will have the value "Parrot"

4. Checking for a Key or Value:

val hasBird = "Bird" in animals  // true
val hasFish = "Fish" in animals  // false

val containsParrot = animals.containsValue("Parrot")  // true

5. Iterating through a HashMap:

for ((key, value) in animals) {
    println("$key -> $value")
}

6. Removing Entries:

animals.remove("Bird")  // Removes the key-value pair for "Bird"

7. Size and Other Properties:

val size = animals.size  // Returns the number of key-value pairs
val keys = animals.keys  // Returns a set of all keys
val values = animals.values  // Returns a collection of all values

8. Combining Maps:

You can use the putAll method to add all key-value pairs from another map:

val moreAnimals = hashMapOf("Fish" to "Salmon", "Bird" to "Eagle")
animals.putAll(moreAnimals)

9. Clearing All Entries:

animals.clear()  // Removes all entries from the map

10. Filtering:

You can use the filter function to get a new map that satisfies a particular condition:

val mammals = animals.filter { it.key == "Mammal" }

11. Default Values:

Retrieve a value with a default if the key doesn't exist:

val fish = animals.getOrDefault("Fish", "Unknown")

12. Map transformations:

You can transform the contents of a map using the mapValues or mapKeys function:

val animalLengths = animals.mapValues { it.value.length }

Conclusion:

HashMap is a powerful collection in Kotlin that allows you to store and retrieve data in key-value pairs efficiently. It offers a variety of methods to manipulate, access, and traverse the stored data. Familiarity with HashMap will help you manage data effectively in Kotlin.

  1. Creating a HashMap in Kotlin:

    • Initialize a HashMap.
    val hashMap = HashMap<String, Int>()
    
  2. HashMap initialization and declaration in Kotlin:

    • Initialize and declare a HashMap with values.
    val ages = hashMapOf("Alice" to 25, "Bob" to 30, "Charlie" to 22)
    
  3. Adding and removing elements in a Kotlin HashMap:

    • Add and remove key-value pairs.
    ages["David"] = 28  // Adding
    ages.remove("Charlie")  // Removing
    
  4. Accessing values in a HashMap in Kotlin:

    • Retrieve values using keys.
    val bobAge = ages["Bob"]
    
  5. Iterating over a HashMap in Kotlin:

    • Iterate through key-value pairs.
    for ((name, age) in ages) {
        println("$name is $age years old")
    }
    
  6. HashMap vs mutableMapOf in Kotlin:

    • Understand the difference between HashMap and mutableMapOf.
    val hashMap = HashMap<String, Int>()
    val mutableMap = mutableMapOf<String, Int>()
    
  7. Default values for HashMap in Kotlin:

    • Provide default values when accessing non-existing keys.
    val age = ages.getOrDefault("Eve", 25)
    
  8. Sorting a HashMap in Kotlin:

    • Sort HashMap by keys or values.
    val sortedByName = ages.toSortedMap()
    val sortedByAge = ages.toList().sortedBy { it.second }.toMap()
    
  9. Using HashMap with data classes in Kotlin:

    • Store data classes in a HashMap.
    data class Person(val name: String, val age: Int)
    
    val people = hashMapOf(
        "Alice" to Person("Alice", 25),
        "Bob" to Person("Bob", 30)
    )
    
  10. Handling null values in a Kotlin HashMap:

    • Use nullable types to handle potential null values.
    val nullableAge: Int? = ages["Unknown"]
    
  11. Merging two HashMaps in Kotlin:

    • Combine two HashMaps.
    val additionalAges = mapOf("Eve" to 28, "Frank" to 35)
    ages.putAll(additionalAges)
    
  12. Filtering and transforming values in a Kotlin HashMap:

    • Use filter and map to manipulate values.
    val adults = ages.filter { it.value >= 18 }
    val doubledAges = ages.mapValues { it.value * 2 }