Reputation: 1470
Can the following example be shortened in some way:
val set = mutableSetOf(1, 2, 3, 4, 5)
val x = set.first()
set.remove(x)
Asked differently: Does Kotlin have an operation for sets similar to pop for Stacks? One that returns and removes the element?
Upvotes: 3
Views: 6341
Reputation: 18420
Does Kotlin have an operation for sets similar to pop for Stacks? One that returns and removes the element?
No, there is no such method. But you can write an extension function for set to do that.
fun <T> MutableSet<T>.pop(): T? = this.first().also{this.remove(it)}
Example:
fun <T> MutableSet<T>.pop(): T? = this.first().also{ this.remove(it)}
fun main() {
val set = mutableSetOf(1, 2, 3, 4, 5)
val x = set.pop()
print(x)
}
Upvotes: 1
Reputation: 18547
There doesn't seem to be such a method.
Of course, you can do it in one line with a construction such as:
val x = set.first().also{ set.remove(it) }
And you could write your own extension method to do that:
fun <T> MutableCollection<T>.removeFirst()
= first().also{ remove(it) }
Or (perhaps more efficiently):
fun <T> MutableCollection<T>.removeFirst()
= with(iterator()){ next().also{ remove() }}
The reason that's not already in the standard library is probably that sets are not generally considered to be ordered. As with any collection, you can iterate through the elements (which is why you can call first()
), but the order isn't part of the collection's structure in the same way that it is for Lists and Stacks.
If order does matter, then you might consider using a MutableList
instead; that has a removeAt()
method which does what you want.
If you need ordering and no duplicates, there's linkedSetOf()
which gives a LinkedHashSet — but that doesn't give you a pop operation either.
Upvotes: 3