Kotlin Tutorials

Kotlin Set groupingBy()
Syntax & Examples

Set.groupingBy() extension function

The groupingBy() extension function in Kotlin creates a Grouping source from a set to be used later with one of the group-and-fold operations, using the specified keySelector function to extract a key from each element.


Syntax of Set.groupingBy()

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

fun <T, K> Set<T>.groupingBy(keySelector: (T) -> K): Grouping<T, K>

This groupingBy() extension function of Set creates a Grouping source from a collection to be used later with one of group-and-fold operations using the specified keySelector function to extract a key from each element.

Parameters

ParameterOptional/RequiredDescription
keySelectorrequiredA function that takes an element and returns the key for grouping.

Return Type

Set.groupingBy() returns value of type Grouping.



✐ Examples

1 Grouping integers by even and odd

Using groupingBy() to create a Grouping source from a set of integers by even and odd.

For example,

  1. Create a set of integers.
  2. Use groupingBy() with a keySelector function that groups elements by even and odd.
  3. Print the resulting Grouping source.

Kotlin Program

fun main() {
    val numbers = setOf(1, 2, 3, 4, 5, 6)
    val grouping = numbers.groupingBy { if (it % 2 == 0) "Even" else "Odd" }
    println(grouping)
}

Output

Grouping source with keySelector: (kotlin.Int) -> kotlin.String

2 Grouping strings by their length

Using groupingBy() to create a Grouping source from a set of strings by their length.

For example,

  1. Create a set of strings.
  2. Use groupingBy() with a keySelector function that groups elements by their length.
  3. Print the resulting Grouping source.

Kotlin Program

fun main() {
    val strings = setOf("one", "two", "three", "four", "five")
    val grouping = strings.groupingBy { it.length }
    println(grouping)
}

Output

Grouping source with keySelector: (kotlin.String) -> kotlin.Int

3 Grouping integers by their parity (even/odd) with custom key

Using groupingBy() to create a Grouping source from a set of integers by their parity (even/odd) with a custom key.

For example,

  1. Create a set of integers.
  2. Use groupingBy() with a keySelector function that groups elements by their parity (even/odd) with a custom key.
  3. Print the resulting Grouping source.

Kotlin Program

fun main() {
    val numbers = setOf(1, 2, 3, 4, 5, 6)
    val grouping = numbers.groupingBy { if (it % 2 == 0) "Even" else "Odd" }
    println(grouping)
}

Output

Grouping source with keySelector: (kotlin.Int) -> kotlin.String

Summary

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