Kotlin - Idiomatic way to remove duplicate strings from array?

AlgorithmKotlin

Algorithm Problem Overview


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

Algorithm Solutions


Solution 1 - Algorithm

Use the distinct extension function:

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

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"]

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.


You may find useful:

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjturollaView Question on Stackoverflow
Solution 1 - AlgorithmhotkeyView Answer on Stackoverflow