A mutable set is an extension of a set that supports adding and removing elements. Like a set, a mutable set does not provide its own function, but it does extend two interfaces: set and mutableCollection. Mutable sets also override all functions from their parent interfaces. This means that we can use all functions, including size, isEmpty, add, contains, and retainAll:
fun mutableSetFunction() {
val mutableSetItems : MutableSet<Int> = mutableSetOf(1,1,2,3,3,4,5,5)
var mutableSetIterator = mutableSetItems.iterator()
while (mutableSetIterator.hasNext()) {
print(mutableSetIterator.next())
}
println("")
println("Set size ${mutableSetItems.size}")
var item = 5
var result = mutableSetItems.contains(item)
println("Mutable item contains $item = $result")
result = mutableSetItems.remove(item)
println("Mutable item removed $item = $result")
item = 6
println("$item is added")
mutableSetItems.add(item)
println(mutableSetItems)
// Keep only mentioned items in list
mutableSetItems.retainAll(listOf(2,4,6,8))
// Clear all items
mutableSetItems.clear()
var miniCollection = listOf(1,1,2,3,3)
if (mutableSetItems.size == 0 ) {
println("List is clear, add mini collection")
mutableSetItems.addAll(miniCollection)
println(mutableSetItems)
}
}
Implement this example and check each function of the mutable set one by one.