Kotlin: How to convert list to map with list?

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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)