首页 > 解决方案 > 将列表转换为不同的列表并映射索引

问题描述

我有一个对象列表,我想把它变成一个不同的列表,同时将所有索引映射到新索引。

例子:

列表:["a", "b", "a", "d"]->["a", "b", "d"]

地图:

{
  0: 0, //0th index of original list is now 0th index of distinct list
  1: 1,
  2: 0, //2nd index of original list is now 0th index of distinct list
  3: 2  //3rd index of original list is now 2th index of distinct list
} 

有没有一种简单的方法可以使用单行或在 kotlin 中使用相当简单的解决方案来做到这一点?

标签: kotlindistinct-values

解决方案


以下表达式将执行此操作:

val p = listOf("a", "b", "a", "d").let {
  val set = it.distinct().mapIndexed { i, v -> v to i }.toMap()
  it.mapIndexed { i, v -> i to set.getValue(v) }
}.toMap()

推荐阅读