Collection Operations
In this page:
Sorting a Collection
.sorted() returns a new list with elements in ascending natural order, while .sortedDescending() returns them in descending order -- neither modifies the original list.
Example: Sorting a Collection
fun main() {
val numbers = listOf(5, 2, 8, 1)
println("Sorted: ${numbers.sorted()}")
println("Descending: ${numbers.sortedDescending()}")
}
Login to try C/C++/Java/PHP code in the editor
Searching with find, any, all, none
.find { predicate } returns the first element matching a condition (or null), while .any, .all, and .none test whether some, every, or no element satisfies a condition.
Example: Searching with find, any, all, none
fun main() {
val numbers = listOf(1, 2, 3, 4, 5)
println("First even: ${numbers.find { it % 2 == 0 }}")
println("Any negative: ${numbers.any { it < 0 }}")
println("All positive: ${numbers.all { it > 0 }}")
}
Login to try C/C++/Java/PHP code in the editor
Counting and Summing
.count { predicate } counts how many elements satisfy a condition, while .sum() adds up a collection of numbers directly and .sumBy { } sums a computed Int value from each element.
Example: Counting and Summing
fun main() {
val numbers = listOf(1, 2, 3, 4, 5, 6)
println("Even count: ${numbers.count { it % 2 == 0 }}")
println("Sum: ${numbers.sum()}")
println("Sum of squares: ${numbers.sumBy { it * it }}")
}
Login to try C/C++/Java/PHP code in the editor
Grouping Elements
.groupBy { } partitions a collection into a Map keyed by the result of the given function, gathering all matching elements together under each key.
Example: Grouping Elements
fun main() {
val words = listOf("apple", "banana", "avocado", "blueberry", "cherry")
val grouped = words.groupBy { it.first() }
println(grouped)
}
Login to try C/C++/Java/PHP code in the editor
- Writing a manual
forloop to sort or search a collection when a clearer built-in function like.sorted()or.find()already exists. - Confusing
.sorted()(returns a new sorted list) with.sort()(sorts aMutableListin place); using the wrong one on the wrong collection type. - Forgetting that many of these operations return a new collection rather than modifying the original in place.
.sorted()/.sortedDescending()return a new list sorted in ascending/descending order..find { }returns the first matching element ornull;.any { }/.all { }/.none { }test conditions across the collection..count { }counts matching elements;.sum()/.sumBy { }add up numeric values.- Most of these operations return a new collection or value rather than mutating the original.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: