← Back to Kotlin Course | Chapter 8: Collections | Lesson 4 of 7

Collection Operations

Collection operations are ready-made recipes, like sort or find, that Kotlin gives you so you don't have to write loops for common jobs.

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

markup
fun main() {
    val numbers = listOf(5, 2, 8, 1)
    println("Sorted: ${numbers.sorted()}")
    println("Descending: ${numbers.sortedDescending()}")
}

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

markup
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 }}")
}

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

markup
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 }}")
}

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

markup
fun main() {
    val words = listOf("apple", "banana", "avocado", "blueberry", "cherry")
    val grouped = words.groupBy { it.first() }
    println(grouped)
}
Common Mistakes
  1. Writing a manual for loop to sort or search a collection when a clearer built-in function like .sorted() or .find() already exists.
  2. Confusing .sorted() (returns a new sorted list) with .sort() (sorts a MutableList in place); using the wrong one on the wrong collection type.
  3. Forgetting that many of these operations return a new collection rather than modifying the original in place.
Chapter Summary
  • .sorted()/.sortedDescending() return a new list sorted in ascending/descending order.
  • .find { } returns the first matching element or null; .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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.