📜  Kotlin hashMapOf()(1)

📅  最后修改于: 2023-12-03 15:02:32.163000             🧑  作者: Mango

Kotlin hashMapOf()

hashMapOf() is a function in Kotlin that is used to create a HashMap collection with key-value pairs.

Syntax

The syntax for hashMapOf() function is:

hashMapOf(key1 to value1, key2 to value2, ..., keyN to valueN)
Parameters

The function takes a variable number of key-value pairs as arguments.

  • key1, key2, ..., keyN: Keys of different data types.
  • value1, value2, ..., valueN: Values corresponding to the keys.
Return Value

The hashMapOf() function returns a HashMap collection with the provided key-value pairs.

Example

Here is an example that demonstrates the usage of hashMapOf() function:

fun main() {
    val userMap = hashMapOf(
        "name" to "John Doe",
        "age" to 30,
        "email" to "john@example.com"
    )
    
    println(userMap)
}

Output: {name=John Doe, age=30, email=john@example.com}

In this example, we create a HashMap userMap with three key-value pairs: "name" to "John Doe", "age" to 30, and "email" to "john@example.com". Finally, we print the HashMap which results in {name=John Doe, age=30, email=john@example.com}.

Additional Operations

After creating a HashMap using hashMapOf(), you can perform various operations on it:

Accessing Values

To access values from a HashMap, you can use the get() function or the indexing operator [] with the key:

val name = userMap["name"]
println(name) // Output: John Doe
Modifying Values

To modify values in a HashMap, you can use the put() function or the indexing operator []:

userMap["age"] = 40
println(userMap) // Output: {name=John Doe, age=40, email=john@example.com}
Removing Values

To remove a key-value pair from a HashMap, you can use the remove() function with the key:

userMap.remove("email")
println(userMap) // Output: {name=John Doe, age=40}
Iterating through HashMap

To iterate through the key-value pairs of a HashMap, you can use a for loop or the forEach function:

for ((key, value) in userMap) {
    println("$key: $value")
}

// Output:
// name: John Doe
// age: 40
userMap.forEach { (key, value) ->
    println("$key: $value")
}

// Output:
// name: John Doe
// age: 40

These are just a few examples of the operations that can be performed on a HashMap created with hashMapOf() function.

For more details, you can refer to the official Kotlin documentation on HashMap.

Conclusion

The hashMapOf() function in Kotlin is a convenient way to create and initialize a HashMap with key-value pairs. It provides easy and efficient operations to manipulate and work with hash maps in your Kotlin applications.