Skip to content
AgileLogics
5 min read

Common List Operations

Prerequisites: Lists

Lists come with a large set of functions for sorting, searching, and summarizing.

Example

fun main() {
    val nums = listOf(5, 3, 8, 1, 3)

    println(nums.sorted())
    println(nums.sortedDescending())
    println(nums.distinct())
    println(nums.min())
    println(nums.max())
    println(nums.sum())
    println(nums.average())
    println(nums.count { it == 3 })
    println(nums.take(2))
    println(nums.drop(3))
    println(nums.reversed())
    println(nums.joinToString("-"))
    println(nums.isEmpty())
}

Expected output

[1, 3, 3, 5, 8]
[8, 5, 3, 3, 1]
[5, 3, 8, 1]
1
8
20
4.0
2
[5, 3]
[1, 3]
[3, 1, 8, 3, 5]
5-3-8-1-3
false
  • These functions return new lists; the original is unchanged. A mutable list also has in-place versions such as sort() and reverse().
  • min() and max() throw an exception on an empty list; minOrNull() and maxOrNull() return null instead.
  • { it == 3 } is a lambda — a small piece of code passed to a function. it means "the current element". The Lambdas lesson covers them.

Checking elements

fun main() {
    val ages = listOf(12, 25, 37, 8)

    println(ages.any { it >= 18 })
    println(ages.all { it > 0 })
    println(ages.none { it > 100 })
    println(ages.find { it > 20 })
}
true
true
true
25

find returns the first match, or null.

Practice

Given val scores = listOf(72, 95, 88, 95, 60), print the highest score, the average, and the scores from highest to lowest.

Show solution
fun main() {
    val scores = listOf(72, 95, 88, 95, 60)
    println(scores.max())
    println(scores.average())
    println(scores.sortedDescending())
}
95
82.0
[95, 95, 88, 72, 60]