Introduction to collections

Collections are one of the most important concepts in programming. They are types that represent groups of elements. In Kotlin, the most important collection types are the following:

  • List: This represents an ordered collection of elements. The same elements can occur multiple times. A list’s elements can be accessed by indexes (zero-based integer numbers that reflect elements’ positions). An example might be a list of songs in a queue: the order of the songs is important, and each song can appear in multiple places.

  • Set: This represents a collection of unique elements. It reflects the mathematical abstraction of a set—a group of objects without repetitions. Sets might not respect element order. However, the default set used by Kotlin does respect element order. An example might be a set of winning numbers in a lottery; they must be unique, but their order does not matter.

  • Map: This represents a set of key-value pairs. Keys must be unique, and each of them points to exactly one value. Multiple keys can be associated with the same values. Maps are useful for expressing logical connections between elements. It is also known as a dictionary in some other languages.

There are also arrays, which are typically considered a low-level primitive used by other collections under the hood.

The hierarchy of interfaces

In Kotlin, a whole hierarchy of interfaces is used to represent different kinds of collections. Take a look at the diagram below.

Get hands-on with 1400+ tech skills courses.