Using distinct() function That's all about removing duplicate elements from a list in Kotlin.
We can remove duplicate element in an array by 2 ways: using temporary array or using separate index. To remove the duplicate element from array, the array must be in sorted order. If array is not sorted, you can sort it by calling Arrays. sort(arr) method.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With