Filter a set in Kotlin
This article explores different ways to filter set in Kotlin.
1. Using filter() function
In Kotlin, we can filter the set using the filter() function. Following is a simple example demonstrating usage of this function:
|
1 2 3 4 5 6 |
fun main() { val set: Set<String> = mutableSetOf("C", "C++", "Java", "Kotlin") val clike = set.filter { s: String -> s.startsWith("C") } println(clike) // [C++, C] } |
2. Using for loop
Another approach is to iterate over the set using a for-loop and filter elements using a conditional statement.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
fun main() { val set: Set<String> = mutableSetOf("C", "C++", "Java", "Kotlin") val clike: MutableSet<String> = HashSet() for (s in set) { // filter languages that start with C if (s.startsWith("C")) { clike.add(s) } } println(clike) // [C++, C] } |
3. Using iterator
Alternatively, you can apply a filter using an iterator. The following example uses the remove() function to filter elements.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
fun main() { val set: MutableSet<String> = mutableSetOf("C", "C++", "Java", "Kotlin") val itr = set.iterator() while (itr.hasNext()) { val curr = itr.next() // filter languages that start with C if (!curr.startsWith("C")) { itr.remove() } } println(set) } |
That’s all about filtering 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 :)