Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 134 ยท Collections

Collections Overview

A tour of Kotlin collections: List, Set and Map, read-only vs mutable interfaces, creation functions, the Iterable hierarchy, copies and views, with runnable examples.

Almost every program needs to keep several values together: the items in a shopping cart, the words in a sentence, the scores by player. Kotlin's standard library gives you three main kinds of collection for this, and a very large toolbox of functions for working with them. This lesson is the map of that territory. The next lessons zoom into Lists, Sets, Maps and Arrays; here you learn how the pieces fit together, why Kotlin has separate read-only and mutable interfaces, and which collection to pick.

The three main collection types

Type Idea Duplicates Order Lookup by
List<E> an ordered sequence allowed by position index (list[2])
Set<E> a group of distinct elements not allowed depends on the implementation membership (x in set)
Map<K, V> key to value associations keys unique, values may repeat depends on the implementation key (map["a"])
Kotlin The three collection types side by side

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 [red, green, red, blue], [red, green, blue], {red=1, green=2, blue=3}, then 4, 3, 3, then green, true and 2. The list keeps both reds, the set quietly dropped the duplicate, and the map is printed as key=value pairs.

A Map is not an Iterable and does not extend Collection, but it is part of the collections family and has the same style of functions. Its keys form a Set and its values form a Collection.

Read-only versus mutable

This is the most important design decision in Kotlin collections. Each type exists twice:

Read-only Mutable
List<E> MutableList<E>
Set<E> MutableSet<E>
Map<K, V> MutableMap<K, V>

A List has get, size, contains and the like, but no add or remove. A MutableList extends List and adds them. Choosing the read-only type in a function signature tells the reader and the compiler: "this function only looks".

Kotlin Mutable collections can change, read-only ones cannot

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 [2, 3, 4], true, false, [a, b, c], {apple=5, pear=5} and [1, 2, 3]. Note that MutableSet.add returns true when the element was new and false when it was already there. And note val: the variable growing never changes (it always refers to the same list), but the list's contents do. val versus mutable collection are two independent decisions; see Variables: val and var.

Calling add on a read-only list is a compile error, not a surprise at run time:

Kotlin No add on a read-only 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 compiler says main.kt:3:11: error: unresolved reference 'add' on receiver of type 'List<String>'. Use mutableListOf when you really need to change the list, or build a new one with names + "Grace".

Read-only does not mean immutable

A List<E> is only a read-only view. It promises that you cannot modify it through that reference, but another reference to the same object might:

Kotlin A read-only view of a changing list

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.

This prints [1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4] and [1, 2, 3, 4, 5]. view and source are the same object seen through two types, so view "changed" when source did. toList() made a real copy, which stayed at four elements. Remember this whenever you hand out a list from a class: returning your internal MutableList as List still lets a caller cast it back, and callers also see later changes. Return toList() when you need a snapshot (see Encapsulation and Design).

On the JVM, listOf(...) returns a Java list implementation and mutableListOf() an ArrayList. Casting a List to MutableList may even work by accident; do not rely on or write code that does it. If a collection must be truly unchangeable, copy it and never share the mutable original.

Creating collections

Each type has creation functions. The most common ones:

Kotlin Creation functions

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 get [10, 20, 30], [], [], [0, 1, 4, 9, 16], [x, y, z], [1, 2], then [3, 1, 2], [b, a], [1], {1=one, 2=two}, {k=1, j=2} and {a=2, z=1}. A few details:

  • List(5) { ... } is a function that builds a list from an index, written like a constructor.
  • buildList and buildMap let you fill a mutable collection inside a lambda and return a read-only result. They are the idiomatic way to build a collection with some logic.
  • emptyList<String>() needs the type because nothing else tells the compiler the element type.
  • setOf and mapOf keep insertion order (they return LinkedHashSet and LinkedHashMap), which is why s1 is [3, 1, 2]. hashSetOf does not promise any order, and sortedMapOf sorts by key.

Pick the type from the question you ask

  • Do you care about position or need duplicates? Use List.
  • Do you mostly ask "is x in here?" or need to remove duplicates? Use Set.
  • Do you look things up by a key? Use Map.
  • Is the size fixed and are the elements primitives, in performance-critical code? Consider an Array.

The Iterable hierarchy

Under the hood the types form a small family tree:

TEXT
Iterable<T>
  Collection<T>
    List<T>
    Set<T>
Map<K, V>         (separate, not an Iterable)

Iterable<T> is anything you can walk through with a for loop. Collection<T> adds size, isEmpty() and contains. List and Set build on it. Most extension functions (map, filter, first, sum...) are defined on Iterable<T>, so they work for lists, sets, ranges and even your own classes that implement Iterable. Writing a function that accepts the broadest type it needs makes it more reusable:

Kotlin Accept Iterable, work with everything

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 five lines are 3 items, total 15, 2 items, total 3, 10 items, total 55, 2 items, total 15 and 0 items, total 0. One function serves a list, a set, a range and a map's values. If it only needs to read, take Iterable/Collection/List; reserve MutableList parameters for functions whose job is to change the list.

Looping over collections

Use for for all of them. For a list you may also want the index, and for a map you get key and value together through destructuring:

Kotlin Looping

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.

This prints the three fruits, then 0: apple, 1: banana, 2: cherry, then Ada is 36 and Alan is 41, and finally 5, 6, 6. The Loops lesson covers for in general.

Operators you will use all the time

Collections support a handful of operators:

  • list[i], map[key], x in collection, x !in collection
  • + and - create a new collection with an element added or removed (on read-only collections)
  • += and -= mean "modify in place" for a mutable collection, and "reassign the variable" for a read-only collection held in a var

That last rule can bite. Both lines below look the same but behave differently:

Kotlin plusAssign versus reassignment

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 [1, 2, 3], [1, 2, 3] and [1, 2]. For readOnly, += built a brand new list and assigned it to the variable; before still holds the old one. If you declare val readOnly = listOf(1, 2) and write readOnly += 3, the compiler stops you with error: 'val' cannot be reassigned., because the only way to read-only-add is to build a new list and assign it. A var holding a MutableList is the confusing case, where both plus and plusAssign could apply; keep one style per variable (val plus a mutable list, or var plus a read-only list) and you will never have to think about it.

Null elements and nullable collections

The element type may be nullable, and the collection itself may be nullable. They are different things:

  • List<String?>: a list that may contain null elements.
  • List<String>?: a list that may itself be null.

In practice prefer an empty collection to a nullable one. emptyList() is just as easy to handle as null but needs no ?. everywhere. For lists with null elements, filterNotNull() returns a List<String>. See Null Safety.

Performance in one paragraph

On the JVM ArrayList gives fast indexing and fast appends, but removing from the front is O(n). HashSet and HashMap give roughly constant-time lookups, while the linked variants (the ones setOf and mapOf use) add a small ordering cost. A List.contains is a linear scan, so checking membership in a big list inside a loop becomes slow; convert it to a Set first. Chains of map/filter on big lists create an intermediate list at each step; the Sequences lesson shows how to avoid that.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which type guarantees that you cannot call add on it?

    List is the read-only interface and has no add. The mutable types add it.
  2. 2. What does setOf(3, 1, 2, 3) print?

    A set drops duplicates, and setOf keeps the insertion order, so the result is [3, 1, 2].
  3. 3. You write val view: List<Int> = source where source is a MutableList. What happens if source.add(9) runs later?

    A read-only type is a view of the same object. Use toList() to take a snapshot copy.
  4. 4. Which is a good parameter type for a function that only needs to loop over the numbers it receives?

    The broadest type that provides what you need makes the function usable with lists, sets, ranges and more.
  5. 5. Which description of Map<K, V> is correct?

    A map associates unique keys with values; many keys can share one value. Sorting happens only with a sorted implementation.

Summary

  • Kotlin has three main collection kinds: List (ordered, duplicates allowed), Set (distinct elements) and Map (key to value).
  • Each has a read-only interface and a Mutable... version; prefer read-only types in signatures.
  • Read-only is a view, not true immutability; copy with toList(), toSet() or toMap() for a snapshot.
  • Create collections with listOf, mutableListOf, setOf, mapOf, List(n) { }, buildList and buildMap.
  • Iterable and Collection are the common supertypes for List and Set; accept the broadest one you need.
  • += mutates a mutable collection but reassigns a var holding a read-only one.

Next: Lists