https://kotlinlang.org logo
Title
d

Daniele B

05/17/2021, 7:44 PM
is there a list structure in Kotlin which keeps distinct values only?
e.g.  val list = listOf(3,9,1,6,7)
if I add a new 9, it would removes the old one:
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
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 ^^
public fun <T> Iterable<T>.distinct(): List<T> {
    return this.toMutableSet().toList()
}
pretty convenient for a stdlib as it is