Kotlin provides a rich set of operations for working with collections, making data manipulation efficient and expressive. These operations allow developers to transform, filter, and analyze data with ease.
Filtering operations allow you to select elements from a collection based on a predicate. The filter()
function is commonly used for this purpose.
val numbers = listOf(1, 2, 3, 4, 5)
val evenNumbers = numbers.filter { it % 2 == 0 }
println(evenNumbers) // Output: [2, 4]
Mapping operations transform each element in a collection. The map()
function applies a given function to each element, creating a new collection.
val numbers = listOf(1, 2, 3, 4, 5)
val squared = numbers.map { it * it }
println(squared) // Output: [1, 4, 9, 16, 25]
Reducing operations combine all elements in a collection to produce a single result. The reduce()
function is commonly used for this purpose.
val numbers = listOf(1, 2, 3, 4, 5)
val sum = numbers.reduce { acc, num -> acc + num }
println(sum) // Output: 15
The groupBy()
function allows you to group elements based on a key selector function.
val words = listOf("apple", "banana", "cherry", "date")
val grouped = words.groupBy { it.length }
println(grouped) // Output: {5=[apple], 6=[banana, cherry], 4=[date]}
The flatten()
function combines nested collections into a single list.
val nestedList = listOf(listOf(1, 2), listOf(3, 4))
val flattened = nestedList.flatten()
println(flattened) // Output: [1, 2, 3, 4]
Kotlin's collection operations provide powerful tools for data manipulation. By mastering these operations, developers can write more expressive and efficient code. For more advanced usage, explore Kotlin Higher-Order Functions and Kotlin Extension Functions.