Hello, I just started learning Kotlin. I am trying...
# getting-started
a
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')
👋 2
s
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.
thank you color 1
c
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:
Copy code
list.sort()   // mutates
list.sorted() // immutable copy
👍 1
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
2
k
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
Ahah, thanks for the precision
e
if it's a mutable collection,
Copy code
charList.retainAll(mutableSetOf<Char>()::add)
will remove all duplicates
👏 3
K 4
c
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
this is equivalent to
Copy code
val set = mutableSetOf<Char>()
charList.retainAll { set.add(it) }
which is equivalent to
Copy code
val set = mutableSetOf<Char>()
val iterator = charList.iterator()
while (iterator.hasNext()) {
    if (!set.add(iterator.next() {
        iterator.remove()
    }
}