Start learning free

LESSON 273 OF 677 · PAIRS, SORTING & BUILT-INS

Min, Max and Sum in Kotlin: Built-in List Functions

Lesson Read the full explanation

TL ; DR:

list.min() gives the smallest value of a list.

list.max() gives the largest value.

list.sum() adds all the values up.


val prices = mutableListOf(4, 9, 2, 7)

println(prices.min())    // 2
println(prices.max())    // 9
println(prices.sum())    // 22


Full lesson:

In Maximum Number In Array, a loop found the largest value. In Sum of Numbers, a loop added numbers up. These jobs come up all the time. Kotlin lists have them built in.

  • list.min() gives the smallest value of the list.
  • list.max() gives the largest value.
  • list.sum() adds all the values up.

maxOf(a, b) from Maximum Number In Array compares two values. max() looks at a whole list.

Watch out for an empty list. min() and max() throw a NoSuchElementException on it. An empty list has no smallest value. minOrNull() and maxOrNull() give null instead. The Elvis operator from Null Safety adds a fallback. So list.minOrNull() ?: 0 gives 0 for an empty list. sum() of an empty list is 0.


Your task

minutes holds how many minutes you practiced coding on each day of a week.

Store the shortest day in shortest and the longest day in longest. Store the week's total in total.

Use the built-ins from this lesson. The code at the bottom prints all three.

Expected output:

shortest = 15
longest = 60
total = 235
STEP 1 OF 3
    Ctrl + Enter to check

    KOTLIN · PAIRS, SORTING & BUILT-INS

    Min Max Sum in Kotlin, explained

    The three built-ins

    Finding the smallest value, the largest value and the total of a list are such common jobs that Kotlin lists have them built in, so no loop is needed:

    • list.min() returns the smallest value.
    • list.max() returns the largest value.
    • list.sum() adds all the values up.
    val prices = mutableListOf(4, 9, 2, 7)
    
    println(prices.min())
    println(prices.max())
    println(prices.sum())
    
    2
    9
    22
    

    Each call looks at every value once. They return a single number, not a list, and they leave the list as it was.

    Don't confuse max() with maxOf(a, b). maxOf compares two values you give it: maxOf(25, 40) is 40. max() is called on a whole list.

    What they replace

    Before, you wrote a loop for each job: one that keeps the largest value seen so far, and one that adds each value to a running total. The built-ins do exactly that work, so the code says what you want and a bug in the loop can't creep in. A call such as minutes.sum() adds the values one by one, like the total-in-a-loop pattern.

    They work on lists of other comparable types too. min() of the words "pear", "fig", "kiwi" is "fig", the first in alphabetical order. For a list of numbers, the average is also built in: minutes.average() returns a decimal number, about 33.57 for the exercise's list.

    Watch out for an empty list

    An empty list has no smallest value. In current Kotlin, min() and max() then throw a NoSuchElementException, so the program stops with an error. If the list can be empty, use the versions that return null instead, and give a fallback with the Elvis operator ?::

    val empty = listOf<Int>()
    println(empty.minOrNull())
    println(empty.minOrNull() ?: 0)
    println(empty.sum())
    
    null
    0
    0
    

    The sum of an empty list is simply 0, so sum() is safe. maxOrNull() does the same for the largest value.

    One more thing to know about sum() on a list of Int: the total is an Int too, so it wraps around past about 2.1 billion. For example listOf(2000000000, 2000000000).sum() gives -294967296. The exercise's numbers are tiny, so it doesn't matter here.

    The exercise

    minutes holds how many minutes you practiced on each day of a week. Store the shortest day in shortest, the longest in longest and the week's total in total, using the built-ins. Each is one line, in a val:

    val minutes = mutableListOf(25, 40, 15, 60, 30, 45, 20)
    
    val shortest = minutes.min()
    val longest = minutes.max()
    val total = minutes.sum()
    
    println("shortest = $shortest")
    println("longest = $longest")
    println("total = $total")
    

    The output:

    shortest = 15
    longest = 60
    total = 235
    

    Check by hand: 25 + 40 + 15 + 60 + 30 + 45 + 20 is 235, the smallest of the seven is 15 and the largest is 60.

    Notice that the exercise needs no loop at all and no if. The three variables are filled by three calls on the same list, and the printing lines at the bottom only read them.

    Common mistakes

    • Forgetting the parentheses. minutes.min without () is not a call.
    • Calling min() on a list that can be empty without a plan for that case. Use minOrNull() and ?:.
    • Expecting a list back. All three return one number.

    Key takeaways

    • min(), max() and sum() replace a loop for the smallest, largest and total.
    • min() and max() throw on an empty list; minOrNull() and maxOrNull() return null.
    • sum() of an empty list is 0.
    Keep going with Kotlin500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free