Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin: How to convert list to map with list?

Tags:

kotlin

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?

like image 317
Elye Avatar asked Nov 01 '17 00:11

Elye


People also ask

How do I map a list to another list 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.

How do I convert a list to 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.


2 Answers

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
like image 64
jrtapsell Avatar answered Oct 04 '22 12:10

jrtapsell


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) 
like image 22
Jacky Choi Avatar answered Oct 04 '22 12:10

Jacky Choi