https://kotlinlang.org logo
Title
a

Arun M

04/28/2023, 9:25 AM
Hello, I just started learning Kotlin. I am trying to remove duplicates in a character mutable list. I did not find appropriate idiom / function to achieve this. Could anyone knowledgeable about this, please help? var charList = ('a', 'a', 'b', 'c', 'c') ----> Expected o/p ('a', 'b', 'c')
s

Sam

04/28/2023, 9:26 AM
My first thought would be the distinct function
That will create a copy of the list. I’m not sure about mutating one. You’ll find that many of the Kotlin idioms and stdlib functions prefer immutability.
c

CLOVIS

04/28/2023, 9:47 AM
For naming conventions: if they're in the past tense, they create a new immutable value, if they're in the present tense, they mutate the current value:
list.sort()   // mutates
list.sorted() // immutable copy
Specifically for this case, there is no efficient way to find duplicates in a
List
. The efficient data structure to avoid duplicates is a
Set
.
.disctint()
actually creates a
Set
, adds all elements to it (thus removing duplicates), then creates a new
List
and adds back all elements to it. Depending on what you want to do, it may be a better idea to use a
Set
from the start and completely avoid
List
here
k

Klitos Kyriacou

04/28/2023, 10:49 AM
Just to be a bit nerdy on naming conventions: they create a new immutable value if they are adjectives. Names like
sorted
are past participle adjectives. Names like
distinct
are just plain vanilla adjectives.
c

CLOVIS

04/28/2023, 11:09 AM
Ahah, thanks for the precision
e

ephemient

04/28/2023, 3:43 PM
if it's a mutable collection,
charList.retainAll(mutableSetOf<Char>()::add)
will remove all duplicates
c

CLOVIS

04/28/2023, 3:45 PM
Wow that's more condensed that I thought possible 😅 I didn't know it was allowed to simultaneously create an instance and use it as a method reference directly, clever
e

ephemient

04/28/2023, 3:46 PM
this is equivalent to
val set = mutableSetOf<Char>()
charList.retainAll { set.add(it) }
which is equivalent to
val set = mutableSetOf<Char>()
val iterator = charList.iterator()
while (iterator.hasNext()) {
    if (!set.add(iterator.next() {
        iterator.remove()
    }
}