更新时间:2023-11-07 10:39:40
使用 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
.
您可能会发现有用: