I am trying to reverse a Map in Kotlin. So far, I have come up with:

mapOf("foo" to 42)
  .toList()
  .map { (k, v) -> v to k }
  .toMap()

Is there any better way of doing this without using a middleman(middlelist)?

推荐答案

由于MapEntry组成,而不是Iterable,您可以改用Map#entries.它将映射到Map#entrySet以创建Set<Entry>的后视图,例如:

val reversed = map.entries.associateBy({ it.value }) { it.key }

OR使用Iterable#associate,这将创建额外的Pair.

val reversed = map.entries.associate{(k,v)-> v to k}

OR使用Map#forEach:

val reversed = mutableMapOf<Int, String>().also {
    //     v-- use `forEach` here     
    map.forEach { (k, v) -> it.put(v, k) } 
}.toMap()
// ^--- you can add `toMap()` to create an immutable Map.

Kotlin相关问答推荐

如何在 Big Data 中使用Inc过滤器?

为什么在Spring中,对事务性方法调用的非事务方法调用仍然在事务中运行?

为什么Kotlin协程程序即使有延迟也能输出?

Android Studio中的只读集合不支持操作失败的原因是什么?

T和T有什么区别:任何>

generic 类实例列表 - 调用采用 T 的函数

如何从 var list 或可变列表中获取列表流

判断 AAR 元数据值时发现的一个或多个问题:

使用最新的 com.jakewharton.rxbinding3:rxbinding:3.0.0-alpha2 库时未找到 RxTextView 和其他小部件

Kotlin 解构超过五个组件

runInTransaction 块内的挂起方法

如何将vararg转换为list?

Kotlin:如何从另一个类访问字段?

在 Kotlin 中创建 Spinner 时,如何在 Fragment 中的旋转屏幕上修复指定为非空的参数为空?

类型不匹配推断类型为单位,但应为空

如何序列化/反序列化Kotlin密封类?

lateinit 的 isInitialized 属性在伴随对象中不起作用

递归方法调用在 kotlin 中导致 StackOverFlowError 但在 java 中没有

Kotlin,什么时候按map授权?

比较Kotlin的NaN