Remove elements from a set in Kotlin
This article explores different ways to conditionally remove elements from a set in Kotlin.
1. Using removeIf() function
The simplest solution is to call the removeIf function, which removes all elements from the set that satisfies the given predicate.
|
1 2 3 4 5 6 7 8 9 10 |
fun removeEven(nums: MutableSet<Int>) { nums.removeIf { it % 2 == 0 } } fun main() { val set = (1..10).toMutableSet() removeEven(set) println(set) // [1, 3, 5, 7, 9] } |
2. Using removeAll() function
Another approach is to create a filtered list of elements that match the given predicate and later pass that list to the removeAll function. This will remove those elements from the original set.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
fun removeEven(nums: MutableSet<Int>) { val collection = ArrayList<Int>() nums.filter { it % 2 == 0 }.map { collection.add(it) } nums.removeAll(collection) } fun main() { val set = (1..10).toMutableSet() removeEven(set) println(set) // [1, 3, 5, 7, 9] } |
3. Using remove() function
You can filter the elements to be removed from the set and then remove those elements from the set using the remove function.
|
1 2 3 4 5 6 7 8 9 10 11 |
fun removeEven(nums: MutableSet<Int>) { nums.filter { it % 2 == 0 } .forEach { nums.remove(it) } } fun main() { val set = (1..10).toMutableSet() removeEven(set) println(set) // [1, 3, 5, 7, 9] } |
4. Using filter() function
To get a new collection of filtered values, you can accumulate elements that match the given condition into a new Set using a filter function.
|
1 2 3 4 5 6 7 8 9 10 |
fun removeEven(nums: MutableSet<Int>): MutableSet<Int> { return nums.filter { it % 2 != 0 }.toMutableSet() } fun main() { val set = (1..10).toMutableSet() val filtered = removeEven(set) println(filtered) // [1, 3, 5, 7, 9] } |
5. Using Iterator
Finally, you can use Iterator’s remove function, which removes the latest element returned by the iterator.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
fun removeEven(nums: MutableSet<Int>) { val it = nums.iterator() while (it.hasNext()) { if (it.next() % 2 == 0) { // remove even elements it.remove() } } } fun main() { val set = (1..10).toMutableSet() removeEven(set) println(set) // [1, 3, 5, 7, 9] } |
That’s all about removing elements from a set in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)