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.
There are 2 variations for the syntax of Set.chunked() extension function. They are:
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>>
.
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>
.
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,
chunked()
function to split the set into chunks of size 2.println
function.fun main(args: Array<String>) {
val numbers = setOf(1, 2, 3, 4, 5, 6)
val chunks = numbers.chunked(2)
println("Chunks: $chunks")
}
Chunks: [[1, 2], [3, 4], [5, 6]]
In Kotlin, we can use the chunked()
function to split a set into chunks and apply a transform function to each chunk.
For example,
chunked()
function to split the set into chunks of size 2 and apply a transform function that concatenates the elements in each chunk.println
function.fun main(args: Array<String>) {
val fruits = setOf("apple", "banana", "cherry", "date", "elderberry")
val chunkedFruits = fruits.chunked(2) { it.joinToString(" & ") }
println("Chunked fruits: $chunkedFruits")
}
Chunked fruits: [apple & banana, cherry & date, elderberry]
In Kotlin, we can use the chunked()
function to split an empty set into chunks, which will result in an empty list.
For example,
chunked()
function to split the empty set into chunks of size 2.println
function.fun main(args: Array<String>) {
val emptySet = emptySet<Int>()
val chunks = emptySet.chunked(2)
println("Chunks: $chunks")
}
Chunks: []
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.