https://kotlinlang.org logo
#getting-started
Title
# getting-started
d

Daniele B

05/17/2021, 7:44 PM
is there a list structure in Kotlin which keeps distinct values only?
Copy code
e.g.  val list = listOf(3,9,1,6,7)
if I add a new 9, it would removes the old one:
Copy code
list.add(9)
println(list) // listOf(3,1,6,7,9)
c

crummy

05/17/2021, 7:49 PM
a set?
val set = setOf(3, 9, 1, 6, 7)
d

Daniele B

05/17/2021, 8:08 PM
Copy code
val set = mutableSetOf(3, 9, 1, 6, 7)
set.add(9)
println(set)
it still prints [3, 9, 1, 6, 7]
I would like it to remove the old one
e

ephemient

05/17/2021, 8:09 PM
mutableSetOf() preserves insertion order. remove and re-add
or build your own LRU, that's a pretty typical CS data structure
👆 5
d

Daniele B

05/17/2021, 8:11 PM
I was hoping Kotlin already had a structure like that
e

ephemient

05/17/2021, 8:15 PM
it's not in any language's stdlib that I know of, partly because it's not that universal: all users wants slightly different things out of it
s

Scott Kruse

05/17/2021, 10:57 PM
yep ^^
Copy code
public fun <T> Iterable<T>.distinct(): List<T> {
    return this.toMutableSet().toList()
}
pretty convenient for a stdlib as it is
2 Views