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
Parameter | Optional/Required | Description |
---|---|---|
action | required | The 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,
- Create a set of integers.
- Use onEach() with an action that prints each element.
- 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,
- Create a set of strings.
- Use onEach() with an action that converts each element to uppercase and prints it.
- 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,
- Create a data class.
- Create a set of custom objects.
- Use onEach() with an action that prints the name of each object.
- 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.