Elye
Elye

Reputation: 60081

Kotlin: How to convert list to map with list?

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?

Upvotes: 39

Views: 20413

Answers (3)

Frank Harper
Frank Harper

Reputation: 3176

Here's a slightly more concise version of Jacky Choi's solution.

It combines the grouping and the transforming into one call to groupBy().

val mapOfList = list
        .groupBy (
            keySelector = { it.name },
            valueTransform = { it.num },
        )

Upvotes: 4

jrtapsell
jrtapsell

Reputation: 7001

Code

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)
}

Output

{a=4, b=2, c=3}
{a=[1, 4], b=[2], c=[3]}

How it works

  • First it takes the list
  • It groups the Combines by their alpha value to their num values

Upvotes: 33

Jacky Choi
Jacky Choi

Reputation: 556

You 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)

Upvotes: 18

Related Questions