I have a list as below {("a", 1), ("b", 2), ("c", 3), ("a", 4)}
I want to convert it to a map of list as below {("a" (1, 4)), ("b", (2)), ("c", (3)))}
i.e. for a, we have a list of 1 and 4, since the key is the same.
The answer in How to convert List to Map in Kotlin? only show unique value (instead of duplicate one like mine).
I tried associateBy
in Kotlin
data class Combine(val alpha: String, val num: Int) val list = arrayListOf(Combine("a", 1), Combine("b", 2), Combine("c", 3), Combine("a", 4)) val mapOfList = list.associateBy ( {it.alpha}, {it.num} ) println(mapOfList)
But doesn't seems to work. How could I do it in Kotlin?
You can use the map() function to easily convert a list of one type to a list of another type. It returns a list containing the results of applying the specified transform function to each element in the original list. That's all about conversion between lists of different types in Kotlin.
To convert List to Set in Kotlin, call toSet() on this list. toSet() returns a new Set created with the elements of this List.
fun main(args: Array<String>) { data class Combine(val alpha: String, val num: Int) val list = arrayListOf(Combine("a", 1), Combine("b", 2), Combine("c", 3), Combine("a", 4)) val mapOfList = list.associateBy ( {it.alpha}, {it.num} ) println(mapOfList) val changed = list .groupBy ({ it.alpha }, {it.num}) println(changed) }
{a=4, b=2, c=3} {a=[1, 4], b=[2], c=[3]}
Combine
s by their alpha value to their num
valuesYou may group the list by alpha
first and then map the value to List<Int>
:
data class Combine(val alpha: String, val num: Int) val list = arrayListOf(Combine("a", 1), Combine("b", 2), Combine("c", 3), Combine("a", 4)) val mapOfList = list .groupBy { it.alpha } .mapValues { it.value.map { it.num } } println(mapOfList)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With