Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin - from a list of Maps, to a map grouped by key

Tags:

kotlin

I have a List<Map<Branch,Pair<String, Any>>> that I would like to convert in a single Map<Branch,List<Pair<String, Any>>> .

So if I have an initial list with simply 2 elements :

List

1. branch1 -> Pair(key1,value1)

   branch2 -> Pair(key2,value2)


2. branch1 -> Pair(key1a,value1a)

I want to end up with :

Map

branch1 -> Pair(key1,value1)

           Pair(key1a,value1a)

branch2 -> Pair(key2,value2)

so a kind of groupBy, using all the values of the keys in the initially nested maps..

I have tried with

list.groupBy{it-> it.keys.first()} 

but obviously it doesn't work, as it uses only the first key. I want the same, but using all keys as individual values.

What is the most idiomatic way of doing this in Kotlin ? I have an ugly looking working version in Java, but I am quite sure Kotlin has a nice way of doing it.. it's just that I am not finding it so far !

Any idea ?

Thanks

like image 784
Vincent F Avatar asked Nov 22 '18 14:11

Vincent F


1 Answers

The following:

val result =
    listOfMaps.asSequence()
        .flatMap {
          it.asSequence()
        }.groupBy({ it.key }, { it.value })

will give you the result of type Map<Branch,List<Pair<String, Any>>> with the contents you requested.

like image 102
Roland Avatar answered Dec 13 '22 15:12

Roland