Kotlin Set onEach()
Syntax & Examples


Set.onEach() extension function

The onEach() extension function in Kotlin performs the given action on each element and returns the collection itself afterwards.


Syntax of Set.onEach()

The syntax of Set.onEach() extension function is:

fun <T, C : Iterable<T>> C.onEach(action: (T) -> Unit): C

This onEach() extension function of Set performs the given action on each element and returns the collection itself afterwards.

Parameters

ParameterOptional/RequiredDescription
actionrequiredThe action to be performed on each element.

Return Type

Set.onEach() returns value of type C.



✐ Examples

1 Performing an action on each element in a set of integers

Using onEach() to print each element in a set of integers.

For example,

  1. Create a set of integers.
  2. Use onEach() with an action that prints each element.
  3. Print the original set to show it is unchanged.

Kotlin Program

fun main() {
    val numbers = setOf(1, 2, 3, 4, 5)
    numbers.onEach { println(it) }
    println(numbers)
}

Output

1
2
3
4
5
[1, 2, 3, 4, 5]

2 Modifying and performing an action on each element in a set of strings

Using onEach() to convert each element to uppercase and print it.

For example,

  1. Create a set of strings.
  2. Use onEach() with an action that converts each element to uppercase and prints it.
  3. Print the original set to show it is unchanged.

Kotlin Program

fun main() {
    val strings = setOf("one", "two", "three")
    strings.onEach { println(it.uppercase()) }
    println(strings)
}

Output

ONE
TWO
THREE
[one, two, three]

3 Performing an action on each custom object in a set

Using onEach() to print the name of each custom object in a set.

For example,

  1. Create a data class.
  2. Create a set of custom objects.
  3. Use onEach() with an action that prints the name of each object.
  4. Print the original set to show it is unchanged.

Kotlin Program

data class Person(val name: String, val age: Int)

fun main() {
    val people = setOf(Person("Alice", 30), Person("Bob", 25), Person("Charlie", 35))
    people.onEach { println(it.name) }
    println(people)
}

Output

Alice
Bob
Charlie
[Person(name=Alice, age=30), Person(name=Bob, age=25), Person(name=Charlie, age=35)]

Summary

In this Kotlin tutorial, we learned about onEach() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.