Is there `OrderedSet` (not sorted) in Kotlin? Any ...
# getting-started
p
Is there
OrderedSet
(not sorted) in Kotlin? Any alternatives?
e
the built-in
setOf()
,
mutableSetOf()
,
mapOf()
,
mutableMapOf()
, and returns of most methods such as
.toSet()
,
.toMap()
, etc. are documented to preserve insertion order
p
How can I get or
takeLast(N)
the last N items in a set without using
reversed().take(N)
? Sets doesn’t seem to support
takeLast
e
iteration order is defined but they are not indexable nor do they provide a reverse iterator, so there is no efficient way to takeLast
p
Any suggestions on an efficient way to 1) have unique values 2) and retrieve last n items? My current solution:
mutableSetOf(1,2,3,1).reversed().take(3).reversed()
e
the most concise you could do is
.toList().takeLast(N)
👌 1
but if this is your only goal I think you'd be better off with a different data structure
p
Any suggestions for a diff data structure that can handle this scenarios?
e
Copy code
val lastN = ArrayDeque<T>(N)
for (item in items) {
    if (lastN.size == n) lastN.removeFirst()
    lastN.addLast(item)
}
p
Thanks! appreciate the quick response 👍
p
Will be a long time before it makes it way into Java (and thus, Kotlin) but this JEP would extend Java collections to allow this: https://openjdk.java.net/jeps/8280836
❤️ 3