Kotlin-从数组中删除重复字符串的惯用方式? [英] Kotlin - Idiomatic way to remove duplicate strings from array?
本文介绍了Kotlin-从数组中删除重复字符串的惯用方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何从Kotlin的Array<String?>
中删除重复项?
How to remove duplicates from an Array<String?>
in kotlin?
推荐答案
使用 distinct
扩展功能:
Use the distinct
extension function:
val a = arrayOf("a", "a", "b", "c", "c")
val b = a.distinct() // ["a", "b", "c"]
还有 distinctBy
函数允许您指定如何区分项目:
There's also distinctBy
function that allows one to specify how to distinguish the items:
val a = listOf("a", "b", "ab", "ba", "abc")
val b = a.distinctBy { it.length } // ["a", "ab", "abc"]
按照 @ mfulton26 的建议,您也可以使用 toMutableSet
,如果您不需要保留原始顺序,请
As @mfulton26 suggested, you can also use toSet
, toMutableSet
and, if you don't need the original ordering to be preserved, toHashSet
. These functions produce a Set
instead of a List
and should be a little bit more efficient than distinct
.
您可能会发现有用:
- Kotlin idioms
- What Java 8 Stream.collect equivalents are available in the standard Kotlin library?
这篇关于Kotlin-从数组中删除重复字符串的惯用方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文