Skip to main content

How to iterate over elements in a HashSet in Kotlin

How to iterate over elements in a HashSet in Kotlin.

Here is a detailed step-by-step tutorial on how to iterate over elements in a HashSet in Kotlin:

  1. Create a HashSet:

    • Start by creating a HashSet using the HashSet constructor. For example, you can create a HashSet of strings as follows:
      val set = HashSet<String>()
  2. Add elements to the HashSet:

    • Use the add function to add elements to the HashSet. For example, let's add some elements to the set:
      set.add("Apple")
      set.add("Banana")
      set.add("Cherry")
  3. Iterate over the elements using a for loop:

    • You can use a for loop to iterate over the elements in the HashSet. In Kotlin, you can use the for loop with the in keyword to iterate over collections. Here's an example:
      for (element in set) {
      println(element)
      }
      This will print each element of the HashSet on a new line.
  4. Iterate over the elements using an iterator:

    • Another way to iterate over the elements in a HashSet is by using an iterator. You can obtain an iterator using the iterator function. Here's an example:
      val iterator = set.iterator()
      while (iterator.hasNext()) {
      val element = iterator.next()
      println(element)
      }
      This will also print each element of the HashSet on a new line.
  5. Iterate over the elements using forEach loop:

    • Kotlin provides a forEach loop that allows you to iterate over elements in a more concise way. You can use it with a lambda expression to perform an action on each element. Here's an example:
      set.forEach { element ->
      println(element)
      }
      This will print each element of the HashSet on a new line.
  6. Iterate over the elements using forEachIndexed loop:

    • If you need to access both the index and the element while iterating, you can use the forEachIndexed loop. It provides an additional index parameter in the lambda expression. Here's an example:
      set.forEachIndexed { index, element ->
      println("Element at index $index is $element")
      }
      This will print each element of the HashSet along with its index.

That's it! You have learned how to iterate over elements in a HashSet in Kotlin using different approaches - a simple for loop, an iterator, and forEach loops. Choose the approach that fits your requirements and coding style.