Kotlin Tutorials

Kotlin Set chunked()
Syntax & Examples

Set.chunked() extension function

The chunked() extension function for sets in Kotlin splits the set into a list of lists, each not exceeding the given size. It can also apply a transform function to each chunk and return a list of the results.


Syntax of Set.chunked()

There are 2 variations for the syntax of Set.chunked() extension function. They are:

1.
fun <T> Set<T>.chunked(size: Int): List<List<T>>

This extension function splits this set into a list of lists each not exceeding the given size.

Returns value of type List<List<T>>.

2.
fun <T, R> Set<T>.chunked(size: Int, transform: (List<T>) -> R): List<R>

This extension function splits this set into several lists each not exceeding the given size and applies the given transform function to each.

Returns value of type List<R>.



✐ Examples

1 Using chunked() to split a set into chunks

In Kotlin, we can use the chunked() function to split a set into a list of lists, each not exceeding the given size.

For example,

  1. Create a set of integers.
  2. Use the chunked() function to split the set into chunks of size 2.
  3. Print the resulting list of lists to the console using the println function.

Kotlin Program

fun main(args: Array<String>) {
    val numbers = setOf(1, 2, 3, 4, 5, 6)
    val chunks = numbers.chunked(2)
    println("Chunks: $chunks")
}

Output

Chunks: [[1, 2], [3, 4], [5, 6]]

2 Using chunked() with a transform function

In Kotlin, we can use the chunked() function to split a set into chunks and apply a transform function to each chunk.

For example,

  1. Create a set of strings.
  2. Use the chunked() function to split the set into chunks of size 2 and apply a transform function that concatenates the elements in each chunk.
  3. Print the resulting list to the console using the println function.

Kotlin Program

fun main(args: Array<String>) {
    val fruits = setOf("apple", "banana", "cherry", "date", "elderberry")
    val chunkedFruits = fruits.chunked(2) { it.joinToString(" & ") }
    println("Chunked fruits: $chunkedFruits")
}

Output

Chunked fruits: [apple & banana, cherry & date, elderberry]

3 Using chunked() with an empty set

In Kotlin, we can use the chunked() function to split an empty set into chunks, which will result in an empty list.

For example,

  1. Create an empty set of integers.
  2. Use the chunked() function to split the empty set into chunks of size 2.
  3. Print the resulting list to the console using the println function.

Kotlin Program

fun main(args: Array<String>) {
    val emptySet = emptySet<Int>()
    val chunks = emptySet.chunked(2)
    println("Chunks: $chunks")
}

Output

Chunks: []

Summary

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