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

Priya

02/09/2022, 8:36 PM
Is there
OrderedSet
(not sorted) in Kotlin? Any alternatives?
e

ephemient

02/09/2022, 8:37 PM
the built-in
setOf()
,
mutableSetOf()
,
mapOf()
,
mutableMapOf()
, and returns of most methods such as
.toSet()
,
.toMap()
, etc. are documented to preserve insertion order
p

Priya

02/09/2022, 8:39 PM
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

ephemient

02/09/2022, 8:40 PM
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

Priya

02/09/2022, 8:44 PM
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

ephemient

02/09/2022, 8:45 PM
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

Priya

02/09/2022, 8:46 PM
Any suggestions for a diff data structure that can handle this scenarios?
e

ephemient

02/09/2022, 8:51 PM
Copy code
val lastN = ArrayDeque<T>(N)
for (item in items) {
    if (lastN.size == n) lastN.removeFirst()
    lastN.addLast(item)
}
p

Priya

02/09/2022, 8:54 PM
Thanks! appreciate the quick response 👍
p

Paul Griffith

02/09/2022, 9:01 PM
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
4 Views