Initialize a map in Kotlin
This article explores different ways to initialize a map in Kotlin.
1. Using mapOf() function
The mapOf() function returns an unmodifiable map from given key/value pairs, which does not permit subsequent addition or removals.
|
1 2 3 4 5 6 7 8 |
fun main() { val immutableMap: Map<String, String> = mapOf( "Red" to "#FF0000", "Blue" to "#0000FF" ) println(immutableMap) // {Red=#FF0000, Blue=#0000FF} } |
2. Using mutableMapOf() function
To get a mutable map of the given key/value pairs, you can use the mutableMapOf() function.
|
1 2 3 4 5 6 7 8 |
fun main() { val mutableMap: HashMap<String, String> = mutableMapOf( "Red" to "#FF0000", "Blue" to "#0000FF" ) as HashMap<String, String> println(mutableMap) // {Red=#FF0000, Blue=#0000FF} } |
3. Using hashMapOf() function
To get a Hashmap instance, use hashMapOf() function. If you need LinkedHashMap, use linkedMapOf() function instead.
|
1 2 3 4 5 6 7 8 |
fun main() { val hashMap: HashMap<String, String> = hashMapOf( "Red" to "#FF0000", "Blue" to "#0000FF" ) println(hashMap) // {Red=#FF0000, Blue=#0000FF} } |
4. Using emptyMap() function
To get an immutable empty map, consider using emptyMap() function.
|
1 2 3 4 5 |
fun main() { val immutableMap: Map<String, String> = emptyMap() println(immutableMap) // {Red=#FF0000, Blue=#0000FF} } |
5. Using Map.of() function
Java 9 made it very convenient to create a compact, unmodifiable instance of a map by providing static factory methods on the java.util.Map interface.
|
1 2 3 4 5 6 7 8 |
fun main() { val immutableMap: Map<String, String> = java.util.Map.of( "Red", "#FF0000", "Blue", "#0000FF" ) println(immutableMap) // {Red=#FF0000, Blue=#0000FF} } |
6. Using Double Brace Initialization
Another alternative is to use Double Brace Initialization, which creates an anonymous inner class with an instance initializer.
|
1 2 3 4 5 6 7 8 9 10 11 |
fun main() { val map: HashMap<String, String> = object : HashMap<String, String>() { init { put("Red", "#FF0000") put("Blue", "#0000FF") } } println(map) // {Red=#FF0000, Blue=#0000FF} } |
That’s all about initializing a map in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)