Kotlin: How to convert a list to a list with a list?

I have a list below {("a", 1), ("b", 2), ("c", 3), ("a", 4)}

I want to convert it to a list map, as shown 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.

Answer in How to convert a list to a map in Kotlin? show only a unique value (instead of a duplicate, like mine).

I tried associateByin 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 it doesn't seem to work. How can I do this in Kotlin?

+4
source share
2 answers

The 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 he takes the list
  • Combine - num
+6

alpha, 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)
+2

Source: https://habr.com/ru/post/1688491/


All Articles