Kotlin-从地图列表到按键分组的地图 [英] Kotlin - from a list of Maps, to a map grouped by key

查看:69
本文介绍了Kotlin-从地图列表到按键分组的地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个List<Map<Branch,Pair<String, Any>>>,我想将其转换为一个Map<Branch,List<Pair<String, Any>>>.

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

因此,如果我有一个仅包含2个元素的初始列表:

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

列表

1. branch1 -> Pair(key1,value1)

   branch2 -> Pair(key2,value2)


2. branch1 -> Pair(key1a,value1a)

我想结束:

地图

branch1 -> Pair(key1,value1)

           Pair(key1a,value1a)

branch2 -> Pair(key2,value2)

是一种groupBy,它使用了最初嵌套的地图中所有键的值.

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

我尝试过

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.

在Kotlin中最惯用的方式是什么?我有一个看起来很丑的Java工作版本,但是我很确定Kotlin有很好的方法来做..只是到目前为止我还没有找到它!

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 !

有什么主意吗?

谢谢

推荐答案

以下内容:

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

会为您提供类型为Map<Branch,List<Pair<String, Any>>>result,其中包含您所请求的内容.

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

这篇关于Kotlin-从地图列表到按键分组的地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆