Sling Academy
Home/Kotlin/Iterating Over Set Elements in Kotlin

Iterating Over Set Elements in Kotlin

Last updated: December 05, 2024

Kotlin, the modern statically-typed language, offers several ways to handle collections. One of these collections is the Set, which is a collection of unique elements. In this article, we will explore different ways to iterate over set elements in Kotlin.

Understanding Sets

In Kotlin, a Set is an unordered collection that does not allow duplicate elements. It is a great choice when you want to ensure that a collection contains only distinct elements.

Creating a Set

Kotlin provides a simple way to create a set using the setOf function:

val mySet = setOf("Kotlin", "Java", "C++")

This creates an immutable set. If you need a mutable set, you can use mutableSetOf:

val mutableMySet = mutableSetOf("Kotlin", "JavaScript", "Python")

Iterating Over a Set

Once you have a set, you might want to perform operations on its elements. Kotlin provides multiple ways to iterate over the elements of a set.

Using a for loop

The straightforward way to iterate over the elements is using a for loop:

for (element in mySet) {
    println(element)
}

This loop iterates over each element in mySet and prints it to the console.

Using the forEach Higher-Order Function

Kotlin collections offer the forEach higher-order function, which makes the code more concise:

mySet.forEach { element ->
    println(element)
}

This function takes a lambda expression and performs the given operation for each element in the set. It makes your code more readable, especially when dealing with complex operations.

Iterating with a Range

Though not specific to Set, Kotlin allows you to use ranges with indices if you have indexed a set:

val indexedSet = mySet.toList()
for (i in indexedSet.indices) {
    println("Element at $i is ${indexedSet[i]}")
}

This approach first converts the set to a list to provide indices. While it's less common with sets due to their unordered nature, it's a good option in scenarios where order matters after conversion.

Using iterator()

If you prefer a more Java-like approach, you can use the iterator() function:

val iterator = mySet.iterator()
while (iterator.hasNext()) {
    println(iterator.next())
}

This method is sometimes useful when working with methods or libraries expecting an iterable input.

Modifying a Mutable Set During Iteration

When working with a mutable set, you may want to modify it during iteration. However, modifying the set directly can throw a ConcurrentModificationException. Rather, you should use a mutable iterator:

val mutableIterator = mutableMySet.iterator()
while (mutableIterator.hasNext()) {
    val item = mutableIterator.next()
    if (item == "JavaScript") {
        mutableIterator.remove()
    }
}

Here, we safely remove "JavaScript" while iterating.

Conclusion

Kotlin provides a rich set of functionalities for iterating over set elements, whether you are adding complexity inside loops using higher-order functions or need to manage iteration through Java-like abstractions. Understanding these approaches enables writing idiomatic and expressive Kotlin code.

Next Article: Understanding Maps in Kotlin: Key-Value Pairs

Previous Article: Checking if a Set Contains a Value in Kotlin

Series: Kotlin Collections

Kotlin

You May Also Like

  • How to Use Modulo for Cyclic Arithmetic in Kotlin
  • Kotlin: Infinite Loop Detected in Code
  • Fixing Kotlin Error: Index Out of Bounds in List Access
  • Setting Up JDBC in a Kotlin Application
  • Creating a File Explorer App with Kotlin
  • How to Work with APIs in Kotlin
  • What is the `when` Expression in Kotlin?
  • Writing a Script to Rename Multiple Files Programmatically in Kotlin
  • Using Safe Calls (`?.`) to Avoid NullPointerExceptions in Kotlin
  • Chaining Safe Calls for Complex Operations in Kotlin
  • Using the Elvis Operator for Default Values in Kotlin
  • Combining Safe Calls and the Elvis Operator in Kotlin
  • When to Avoid the Null Assertion Operator (`!!`) in Kotlin
  • How to Check for Null Values with `if` Statements in Kotlin
  • Using `let` with Nullable Variables for Scoped Operations in Kotlin
  • Kotlin: How to Handle Nulls in Function Parameters
  • Returning Nullable Values from Functions in Kotlin
  • Safely Accessing Properties of Nullable Objects in Kotlin
  • How to Use `is` for Nullable Type Checking in Kotlin