Skip to content
Tutorials Center
My learning

Topics

Lesson 38 of 134 ยท Collections

Aggregates and Folding

Learn Kotlin aggregate functions: sum, count, min, max, average, sumOf, fold, reduce, runningFold, joinToString and groupingBy, with empty-collection pitfalls and overflow traps.

An aggregate boils a whole collection down to one value: a total, a count, the biggest element, a joined string, a final state. Every report, statistic and summary line in a program is an aggregate. Kotlin gives you ready-made functions for the common ones (sum, count, max, average) and two general tools, fold and reduce, that can build any aggregate from a starting value and a combining step.

This lesson covers the built-in aggregates, the difference between fold and reduce, the running variants that keep every intermediate result, and the traps that catch beginners: empty collections, integer overflow and floating-point rounding. You should already be comfortable with lists and lambdas; the previous lesson, Collection Transformations, covers map and filter, which usually come right before an aggregate.

The ready-made aggregates

Kotlin sum, count, min, max, average

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The output is 108, 6, 4, 4, 42, 18.0, 216 and 0.6000000000000001.

  • sum() works on lists of numbers (Int, Long, Double, and the unsigned types). It does not exist for strings or arbitrary objects.
  • count() without arguments is the size; with a predicate it counts matching elements. count { } is clearer than filter { }.size and does not build a list.
  • min() and max() return the smallest and largest element. For anything that is not a number, they work on any Comparable, including strings.
  • average() always returns a Double, even for a list of Int. That is why you see 18.0, not 18.
  • sumOf { } computes a value per element and adds them up. The lambda's result type decides the result type, so sumOf { it * 2L } returns a Long.

The last line shows that floating-point addition is inexact: 0.1 + 0.2 + 0.3 is 0.6000000000000001, not 0.6. That is how Double works in every language, not a Kotlin bug. For money, use whole cents in a Long or BigDecimal; see Working with Numbers.

Aggregating objects: sumOf, maxBy, minOf

Real data is rarely a list of bare numbers. You usually have objects and want an aggregate of one property. The functions with By, Of and sumOf take a lambda that picks the property.

Kotlin Aggregating a shopping cart

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

You see 69.0, 13, 2, bag, bag, 30.0 and bag. Pay attention to the difference between two families:

Function Returns Example result
maxBy { it.price } the element with the largest selector the Item called bag
maxOf { it.price } the largest selector value 30.0

maxBy answers "which book is the longest?"; maxOf answers "how long is the longest book?". The same split exists for minBy and minOf. The OrNull suffix makes the function return null instead of throwing when the collection is empty, which brings us to the biggest trap.

sumOf has one overload per numeric result type (Int, Long, Double, BigDecimal, ...). The lambda's return type picks the overload, so sumOf { it.qty } gives an Int and sumOf { it.price * it.qty } gives a Double. If you want a Long total, return a Long: sumOf { it.qty.toLong() }.

Empty collections: the classic trap

What is the biggest element of an empty list? There is no answer. Kotlin refuses to invent one, so the plain functions throw and the OrNull versions return null:

Kotlin max on an empty list (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The first line prints null. The second crashes with Exception in thread "main" java.util.NoSuchElementException and a stack trace that mentions maxOrThrow; there is no message, so the exception type is the clue. The same rule holds for min, maxBy, minBy and reduce. Pick the variant that matches your intent:

  • Use max() when an empty list would be a bug in your program. The crash tells you early.
  • Use maxOrNull() when empty input is normal, and handle the null with ?: or ?..

Not every aggregate has this problem. Some have a natural answer for "nothing": sum() of an empty list is 0, count() is 0, joinToString() is the empty string, and fold(x) returns x. But average() of an empty list returns NaN ("not a number"), which silently flows through later calculations; check isEmpty() first if that would hurt.

fold and reduce: build any aggregate

sum and max are special cases of a general idea: start with a value, then combine it with each element in turn. fold takes the starting value (the accumulator) explicitly. reduce takes the first element as the starting value.

Kotlin fold, reduce and running variants

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The ten lines are 15, 120, 12345, 12345, 54321, [0, 1, 3, 6, 10, 15], [1, 3, 6, 10, 15], [100, 99, 97, 94, 90, 85], (15, 120) and 40. Walk through a few:

  • fold(0) { acc, x -> acc + x } starts with acc = 0 and for each element replaces acc with the lambda's result: 0, 1, 3, 6, 10, 15. The last value is the answer, 15. With 1 as the start and * as the step it computes the product, 120.
  • reduce { acc, x -> acc * 10 + x } starts with acc = 1 (the first element) and combines the other four elements, building the number 12345.
  • fold("") shows that the accumulator can have a different type from the elements: integers go in, a String comes out. That is the key advantage of fold over reduce, where the result type must equal the element type.
  • foldRight processes from the end, and notice that the lambda parameters swap order: { x, acc -> ... }. It builds 54321.
  • runningFold and runningReduce keep every intermediate accumulator instead of only the last one. scan is the same as runningFold, named after the functional-programming tradition. Running sums are the basis of balances, progress bars and prefix-sum algorithms.
  • The accumulator can be any object, even a Pair that you destructure in the lambda parameters. Here a single pass computes the sum and the product at once: (15, 120).
  • foldIndexed also passes the index: 0*1 + 1*2 + 2*3 + 3*4 + 4*5 = 40.

Rule of thumb: use reduce when you combine elements of the same type and an empty input is a bug; use fold whenever you need a starting value, a different result type, or a safe answer for empty input.

reduce on an empty list

Kotlin reduce on an empty list (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The program prints 0, then null, and then dies with Exception in thread "main" java.lang.UnsupportedOperationException: Empty collection can't be reduced. fold is safe because the starting value is the answer for no elements. reduce has no first element to start from, so it throws, and reduceOrNull returns null instead.

Joining and testing

Two last families round out the toolbox. joinToString aggregates into one String, and the predicates any, all and none aggregate into one Boolean.

Kotlin joinToString, any, all, none

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The output starts with kotlin, is, concise, and, safe, then <kotlin-is-concise-and-safe>, kotlin, is, concise, ... and KOTLIN, IS, CONCISE, AND, SAFE. The three predicates all print true: some word is longer than six letters, every word is non-empty, and no word equals java. Then comes {6=1, 2=1, 7=1, 3=1, 4=1} (how many words have each length) and {k=6, i=2, c=7, a=3, s=4}.

groupingBy is worth knowing: it groups lazily and lets you run an aggregate (eachCount, fold, reduce, aggregate) per group without first building the lists that groupBy would. For counting, groupingBy { }.eachCount() is the idiom; see Maps.

Remember that any, all and none have well-defined answers for an empty list: any is false, all is true (vacuous truth: no element breaks the rule) and none is true. More about them in Accessing and Searching.

Overflow and precision

Aggregates do plain arithmetic, so they inherit the limits of the number types.

Kotlin Overflow and rounding

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The first sum prints -2147483648: Int.MAX_VALUE + 1 wraps around silently, with no exception. Summing as Long gives the correct 2147483648. For lists of Int that might add up beyond two billion (file sizes, view counts, cents), accumulate in a Long. Comparing a floating-point sum with == is false here (0.1 + 0.1 + 0.1 is 0.30000000000000004), so compare with a tolerance. average() of [1, 2] is 1.5, but listOf(1, 2, 3, 4).sum() / 4 divides two Ints and prints 2 instead of 2.5. Use average() and let it return a Double. Finally, the percentage shares come out as [50.0, 16.7, 33.3].

Aggregating maps

Maps are aggregated through their values, keys or entries, or directly with the same functions, which take an entry as it:

Kotlin Aggregating a map

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The results are 20, b, 20, 2 and a=3. maxByOrNull { it.value }?.key is the idiom for "the key with the largest value". Note that minBy on a map returns the whole entry, printed as a=3.

When to use what

  • Plain sum, count, max, average for simple lists of numbers.
  • sumOf, maxBy, minOf when the numbers live inside objects.
  • fold when you need a custom result, a different type or a safe empty answer; reduce when empty is a bug.
  • runningFold when you need every intermediate state, such as balances after each transaction.
  • A plain for loop with a few vars is still fine if you compute five aggregates in one pass and a fold with a tuple would be hard to read.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does emptyList<Int>().sum() return?

    The sum of nothing is 0. max() would throw, and average() returns NaN, but sum() has a natural answer.
  2. 2. Which call is safe on a list that might be empty?

    maxOrNull() returns null for an empty list; the other three throw.
  3. 3. What is the difference between maxBy { it.price } and maxOf { it.price }?

    By returns the element whose selector is the largest; Of returns the selector value itself.
  4. 4. What does listOf(1, 2, 3).runningFold(0) { acc, x -> acc + x } return?

    runningFold keeps the initial value and every intermediate accumulator: 0, 1, 3, 6.
  5. 5. Why does listOf(Int.MAX_VALUE, 1).sum() print a negative number?

    Int arithmetic overflows silently and wraps to -2147483648. Use sumOf { it.toLong() } to avoid it.

Summary

  • sum, count, min, max and average cover the common cases; average() always returns a Double.
  • sumOf, maxBy/minBy (element) and maxOf/minOf (value) aggregate a property of objects.
  • On empty input max, min, maxBy and reduce throw; their OrNull versions return null; sum() is 0 and average() is NaN.
  • fold(initial) { acc, x -> ... } can build any result, of any type; reduce starts with the first element and needs a non-empty collection.
  • runningFold, runningReduce and scan return every intermediate accumulator.
  • joinToString builds strings; any, all and none build booleans; groupingBy aggregates per group.
  • Int sums overflow silently and Double sums are inexact; accumulate in Long or BigDecimal when it matters.

Next: Sorting and Comparators