How to convert a List to a Map in Kotlin?
Hi everyone! I just started learning Kotlin and came across this task. I have a list of objects (data class), for example, a list of users:
```kotlin
data class User(val id: Int, val name: String)
val users = listOf(
User(1, "Alice"),
User(2, "Bob"),
User(3, "Charlie")
)
```
I need to convert this list into a Map, where the key is `id` and the value is the `User` object itself (or its name). In Java, I would use loops or the Stream API, but in Kotlin, as I understand, there are more concise ways.
I tried writing something like `users.map { it.id to it }`, but this returns a list of pairs, not a Map. Then I found the `toMap()` method, but it doesn't always work as I expect, especially if there are duplicate keys.
Please advise how to correctly and concisely convert a List to a Map in Kotlin?
No answers yet.
Log in to leave an answer
Blogs
stdClass in PHP: What It Is and How to Use It (Tutorial)
TypeScript on All Fronts: How to Write Code for Web, Mobile, and Desktop
WebAssembly and Rust: What They Are and Why You Should Know About Them
Adding Elements to an Empty PHP Array: What Happens "Under the Hood"?