简体   繁体   English

Kotlin是否有办法展平地图 <K out T , List<V out T> 列出 <T>

[英]Kotlin Is there a way to flatten Map<K out T , List<V out T> to List<T>

I would like to transform the Map to List 我想将地图转换为列表

eg I have 例如我有

mapOf("a" to listOf(1,2),
      "b" to listOf(3,4)
)

I want the result to be 我希望结果是

listOf("a", 1, 2, "b", 3, 4)

order must be Key and its Values, Key and its Values, ... 订单必须是键及其值,键及其值,...

is there some function in kotlin that could help me with that? Kotlin中有一些功能可以帮助我吗?

My second comment variant as answer for a Map<String, List<Int>> : 我的第二个注释变体作为Map<String, List<Int>>答案:

mapOf("a" to listOf(1,2),
      "b" to listOf(3,4))
     .flatMap { (key, values) -> listOf(key) + values }

which gives a List<Any> with the keys followed by their values. 它给出一个List<Any> ,其后跟键的值。

This example makes use of destructuring declaration and Map.flatMap . 本示例使用了解构声明Map.flatMap

UPDATE : the answer below was written before the question was updated and changed how the map was created (see the history of the question for details). 更新 :下面的答案是在更新问题和更改地图创建方式之前编写的(有关详细信息,请参阅问题的历史记录)。 As the question now stands, the answer below will no longer work. 按照现在的问题,下面的答案将不再起作用。 It does work for the question as originally asked though, I believe. 我相信,它确实可以解决最初提出的问题。

@Roland is right that your map will never result in that list because there can only ever be a single value in the map against any given key. @Roland是正确的,因为您的地图永远不会出现在该列表中,因为针对任何给定的键,地图中只能有一个值。 So I think you need to replace that map with a list of pairs. 因此,我认为您需要用成对列表替换该映射。 You can then group it and flatmap it to get your desired result: 然后,您可以将其分组并进行平面布置图以获得所需的结果:

val pairs = listOf("a" to 1, "a" to 2, "b" to 3, "b" to 4)
val result = pairs
        .groupBy { it.first }
        .flatMap { (key, values) -> listOf(key).plus(values.map { it.second }) }

Another slightly different option which you might decide is more readable is this: 您可能会决定的另一个稍微不同的选项更具可读性:

val result = pairs
        .groupBy({ it.first }, { it.second })
        .flatMap { (key, values) -> listOf(key).plus(values) }

You can flatMap over map.entries . 您可以在map.entries进行flatMap Have a look at this function : 看一下这个功能

val map = mapOf("a" to listOf(1,2), 
                "b" to listOf(3,4))
println(map)
val flattened : List<Any> = map.entries.flatMap {entry -> 
    //create list with key as only element, must be type <Any> to add other stuff later
    val list = mutableListOf<Any>(entry.key)
    //add values
    list.addAll(entry.value)
    list
}
println(flattened)

prints: 印刷品:

{a=[1, 2], b=[3, 4]}
[a, 1, 2, b, 3, 4]

@Rolands answer inspired this even simpler, more idiomatic version. @Rolands的答案启发了这个更简单,更惯用的版本。 It essentially does the same, but crams everything into one line: 本质上是一样的,但是将所有内容都塞进一行:

 val flattened: List<Any> = map.flatMap {entry -> 
        listOf(entry.key) + entry.value
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM