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"]
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:
Kotlin idioms
What Java 8 Stream.collect equivalents are available in the standard Kotlin library?
Success story sharing
toSet
ortoMutableSet
which have less overhead thandistinct
and if ordering does not matter you can usetoHashSet
.to*Set
is more efficient (space & time) thandistinct[By]
because it returns theSet
directly instead of using aSet
internally and converting it to aList
as its return value and 2)distinctBy
is can be more efficient thandistinct
simply because you can avoid full object equality comparison. Both are valid points. I ran with your statement that "certainly it doesn't always have overhead" and I was replying to that and overlooked that you were comparingdistinct
withdistinctBy
(and not withto*Set
).Iterable.distinct
actually doestoMutableSet().toList()
internally. So don't worry about performance :-)