gpt4 book ai didi

带条件的 Kotlin distinctBy

转载 作者:行者123 更新时间:2023-12-02 12:35:56 26 4
gpt4 key购买 nike

我有多个具有相同键的对象的数组,其他对象具有空值,我希望使用 distinctBy 删除重复项并获取值具有最长字符串的对象。

data class ObjA(val key: String, val value: String)

fun test() {
val listOfA = mutableListOf(
ObjA("one", ""), //This will be taken in distinctBy.
ObjA("one", "o"),
ObjA("one", "on"),
ObjA("one", "one"), //This will be ignored in distinctBy. I WANT THIS ONE.

ObjA("two", ""), //This will be returned in distinctBy
ObjA("two", "2"),
ObjA("two", "two"), //But I want this.

ObjA("three", "3"),
ObjA("four", "4"),
ObjA("five", "five")
)

val listOfAWithNoDuplicates = listOfA.distinctBy { it.key }

for (o in listOfAWithNoDuplicates) {
println("key: ${o.key}, value: ${o.value}")
}
}

输出
key: one, value: 
key: two, value:
key: three, value: 3
key: four, value: 4
key: five, value: five

如何使这项工作。任何帮助将不胜感激。

最佳答案

distinctBy 只需根据您的选择器(并按照列表的顺序)返回不同的键,您最终会得到唯一的键,但还没有您想要的值。

对于那个特定的用例,我可能只是 sort前面是 distinctBy

listOfA.sortedByDescending { it.value.length }
.distinctBy { it.key }

sortedByDescending 创建一个新列表或者您只是事先对当前列表进行排序( sortByDescending )并应用 distinctBy稍后,例如:
listOfA.sortByDescending { it.value.length }
listOfA.distinctBy { it.key }

在这两种情况下,您都会得到一个新的 List<ObjA>与预期值。

我还想到了其他几种变体。所有这些变体都会将结果放入 Map<String, ObjA>其中 key 实际上是唯一的 ObjA.key .您可能想调用 .values如果您对 key 不感兴趣,请直接/ ObjA -映射。
  • 使用 groupingBy 的变体和 reduce :
    listOfA.groupingBy { it.key }
    .reduce { _, acc, e->
    maxOf(e, acc, compareBy { it.value.length })
    }
  • 使用普通的变体 forEach /for并填写自己的 Map :
    val map = mutableMapOf<String, ObjA>()
    listOfA.forEach {
    map.merge(it.key, it) { t, u ->
    maxOf(t, u, compareBy { it.value.length })
    }
    }
  • 使用 fold 的变体和 merge (与之前的非常相似......只是使用 fold 而不是 for/forEach ):
    listOfA.fold(mutableMapOf<String, ObjA>()) { acc, objA ->
    acc.apply {
    merge(objA.key, objA) { t, u ->
    maxOf(t, u, compareBy { it.value.length })
    }
    }
    }
  • 使用 groupBy 的变体其次是 mapValues (但您实际上是在创建 1 张您立即丢弃的 map ):
    listOfA.groupBy { it.key } // the map created at this step is discarded and all the values are remapped in the next step
    .mapValues { (_, values) ->
    values.maxBy { it.value.length }!!
    }
  • 关于带条件的 Kotlin distinctBy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56255078/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com