What is the idiomatic way to remove duplicate strings from array?

Technology CommunityCategory: KotlinWhat is the idiomatic way to remove duplicate strings from array?
VietMX Staff asked 4 years ago
Problem

How to remove duplicates from an Array<String?> in Kotlin?

Use the distinct extension function:

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

You can also use:

  • toSettoMutableSet
  • toHashSet – if you don’t need the original ordering to be preserved

These functions produce a Set instead of a List and should be a little bit more efficient than distinct.