← 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.
Syntax
kotlin
list.sorted()
list.sortedDescending()
list.find { condition }
list.any { condition }
list.all { condition }
list.count { condition }
list.sum()

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
// Entry point: execution of the program starts here
fun main() {
    // Declare a read-only variable `numbers`, set to `listOf(5, 2, 8, 1)`
    val numbers = listOf(5, 2, 8, 1)
    // Print "Sorted: ${numbers.sorted()}" to the console, with a trailing newline
    println("Sorted: ${numbers.sorted()}")
    // Print "Descending: ${numbers.sortedDescending()}" to the console, with a trailing newline
    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
// Entry point: execution of the program starts here
fun main() {
    // Declare a read-only variable `numbers`, set to `listOf(1, 2, 3, 4, 5)`
    val numbers = listOf(1, 2, 3, 4, 5)
    // Print "First even: ${numbers.find { it % 2 == 0 }}" to the console, with a trailing newline
    println("First even: ${numbers.find { it % 2 == 0 }}")
    // Print "Any negative: ${numbers.any { it < 0 }}" to the console, with a trailing newline
    println("Any negative: ${numbers.any { it < 0 }}")
    // Print "All positive: ${numbers.all { it > 0 }}" to the console, with a trailing newline
    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
// Entry point: execution of the program starts here
fun main() {
    // Declare a read-only variable `numbers`, set to `listOf(1, 2, 3, 4, 5, 6)`
    val numbers = listOf(1, 2, 3, 4, 5, 6)
    // Print "Even count: ${numbers.count { it % 2 == 0 }}" to the console, with a trailing newline
    println("Even count: ${numbers.count { it % 2 == 0 }}")
    // Print "Sum: ${numbers.sum()}" to the console, with a trailing newline
    println("Sum: ${numbers.sum()}")
    // Print "Sum of squares: ${numbers.sumBy { it * it }}" to the console, with a trailing newline
    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
// Entry point: execution of the program starts here
fun main() {
    // Declare a read-only variable `words`, set to `listOf("apple", "banana", "avocado", "blueberry", "cherry")`
    val words = listOf("apple", "banana", "avocado", "blueberry", "cherry")
    // Declare a read-only variable `grouped`, set to `words.groupBy { it.first() }`
    val grouped = words.groupBy { it.first() }
    // Print `grouped` to the console, with a trailing newline
    println(grouped)
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
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.