且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间: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.

您可能会发现有用:

  • Kotlin idioms
  • What Java 8 Stream.collect equivalents are available in the standard Kotlin library?