0
0
Kotlinprogramming~5 mins

Take, drop, and chunked in Kotlin

Choose your learning style9 modes available
Introduction

These functions help you work with parts of a list easily. You can grab some items, skip some, or split the list into smaller groups.

When you want to get the first few items from a list, like the first 3 names in a guest list.
When you want to ignore the first few items and work with the rest, like skipping the first 2 messages in a chat.
When you want to split a long list into smaller chunks, like dividing a list of students into groups of 4.
Syntax
Kotlin
val result = list.take(n)
val result = list.drop(n)
val result = list.chunked(size)

take(n) gets the first n items from the list.

drop(n) skips the first n items and returns the rest.

chunked(size) splits the list into smaller lists each with size items.

Examples
This gets the first 2 numbers: [1, 2]
Kotlin
val numbers = listOf(1, 2, 3, 4, 5)
val firstTwo = numbers.take(2)
This skips the first 2 numbers and returns [3, 4, 5]
Kotlin
val numbers = listOf(1, 2, 3, 4, 5)
val afterTwo = numbers.drop(2)
This splits the list into chunks of 2: [[1, 2], [3, 4], [5]]
Kotlin
val numbers = listOf(1, 2, 3, 4, 5)
val chunks = numbers.chunked(2)
Sample Program

This program shows how to use take, drop, and chunked on a list of fruits.

Kotlin
fun main() {
    val fruits = listOf("apple", "banana", "cherry", "date", "fig", "grape")

    val firstThree = fruits.take(3)
    println("First three fruits: $firstThree")

    val afterThree = fruits.drop(3)
    println("Fruits after first three: $afterThree")

    val groupsOfTwo = fruits.chunked(2)
    println("Fruits in groups of two: $groupsOfTwo")
}
OutputSuccess
Important Notes

If take(n) asks for more items than the list has, it just returns the whole list.

drop(n) returns an empty list if you drop more items than the list contains.

chunked(size) creates the last chunk with fewer items if the list size isn't a multiple of size.

Summary

take(n) gets the first n items from a list.

drop(n) skips the first n items and returns the rest.

chunked(size) splits a list into smaller lists of the given size.