algorithm - Kotlin - 从数组中删除重复字符串的惯用方法?

标签 algorithm kotlin

如何从 Array<String?> 中删除重复项在 kotlin 中?

最佳答案

使用 distinct extension function :

val a = arrayOf("a", "a", "b", "c", "c")
val b = a.distinct() // ["a", "b", "c"]

还有distinctBy function这允许人们指定如何区分项目:

val a = listOf("a", "b", "ab", "ba", "abc")
val b = a.distinctBy { it.length } // ["a", "ab", "abc"]

作为 @mfulton26建议,也可以使用toSet , toMutableSet并且,如果您不需要保留原始订单,toHashSet .这些函数产生一个 Set 而不是 List 并且应该比 distinct 更高效一些。


您可能会觉得有用:

关于algorithm - Kotlin - 从数组中删除重复字符串的惯用方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40430297/

相关文章:

将二分图简化为树/森林的算法设计(有约束)

algorithm - 多项式乘法复杂度降低

algorithm - 数字字符串的压缩

algorithm - 凸包 : known number of points but not points itself

algorithm - 在网格行走中获得高分

kotlin - 是否有任何理由使用 suspend fun fn(...) : Either<Throwable, A> 而不是 suspend fun fn(...) : A?

kotlin - 在 Kotlin 中声明空集合

android - 为什么项目可以在没有工厂的情况下创建带有构造函数参数的ViewModel类的实例

android - 如何在约束布局中动态设置权重

android - 如何使用 Kotlin 将我计算机中托管的 MySQL 连接到 Android 应用程序