Constructing Collections

Constructing from elements

The most common way to create a collection is with the standard library functions listOf<T>(), setOf<T>(), mutableListOf<T>(), mutableSetOf<T>(). If you provide a comma-separated list of collection elements as arguments, the compiler detects the element type automatically. When creating empty collections, specify the type explicitly.

  1. val numbersSet = setOf("one", "two", "three", "four")
  2. val emptySet = mutableSetOf<String>()

The same is available for maps with the functions mapOf() and mutableMapOf(). The map’s keys and values are passed as Pair objects (usually created with to infix function).

  1. val numbersMap = mapOf("key1" to 1, "key2" to 2, "key3" to 3, "key4" to 1)

Note that the to notation creates a short-living Pair object, so it’s recommended that you use it only if performance isn’t critical. To avoid excessive memory usage, use alternative ways. For example, you can create a mutable map and populate it using the write operations. The apply() function can help to keep the initialization fluent here.

  1. val numbersMap = mutableMapOf<String, String>().apply { this["one"] = "1"; this["two"] = "2" }

Empty collections

There are also functions for creating collections without any elements: emptyList(), emptySet(), and emptyMap(). When creating empty collections, you should specify the type of elements that the collection will hold.

  1. val empty = emptyList<String>()

Initializer functions for lists

For lists, there is a constructor that takes the list size and the initializer function that defines the element value based on its index.

  1. fun main() {
  2. //sampleStart
  3. val doubled = List(3, { it * 2 }) // or MutableList if you want to change its content later
  4. println(doubled)
  5. //sampleEnd
  6. }

Concrete type constructors

To create a concrete type collection, such as an ArrayList or LinkedList, you can use the available constructors for these types. Similar constructors are available for implementations of Set and Map.

  1. val linkedList = LinkedList<String>(listOf("one", "two", "three"))
  2. val presizedSet = HashSet<Int>(32)

Copying

To create a collection with the same elements as an existing collection, you can use copying operations. Collection copying operations from the standard library create shallow copy collections with references to the same elements. Thus, a change made to a collection element reflects in all its copies.

Collection copying functions, such as toList(), toMutableList(), toSet() and others, create a snapshot of a collection at a specific moment. Their result is a new collection of the same elements. If you add or remove elements from the original collection, this won’t affect the copies. Copies may be changed independently of the source as well.

  1. fun main() {
  2. //sampleStart
  3. val sourceList = mutableListOf(1, 2, 3)
  4. val copyList = sourceList.toMutableList()
  5. val readOnlyCopyList = sourceList.toList()
  6. sourceList.add(4)
  7. println("Copy size: ${copyList.size}")
  8. //readOnlyCopyList.add(4) // compilation error
  9. println("Read-only copy size: ${readOnlyCopyList.size}")
  10. //sampleEnd
  11. }

These functions can also be used for converting collections to other types, for example, build a set from a list or vice versa.

  1. fun main() {
  2. //sampleStart
  3. val sourceList = mutableListOf(1, 2, 3)
  4. val copySet = sourceList.toMutableSet()
  5. copySet.add(3)
  6. copySet.add(4)
  7. println(copySet)
  8. //sampleEnd
  9. }

Alternatively, you can create new references to the same collection instance. New references are created when you initialize a collection variable with an existing collection. So, when the collection instance is altered through a reference, the changes are reflected in all its references.

  1. fun main() {
  2. //sampleStart
  3. val sourceList = mutableListOf(1, 2, 3)
  4. val referenceList = sourceList
  5. referenceList.add(4)
  6. println("Source size: ${sourceList.size}")
  7. //sampleEnd
  8. }

Collection initialization can be used for restricting mutability. For example, if you create a List reference to a MutableList, the compiler will produce errors if you try to modify the collection through this reference.

  1. fun main() {
  2. //sampleStart
  3. val sourceList = mutableListOf(1, 2, 3)
  4. val referenceList: List<Int> = sourceList
  5. //referenceList.add(4) //compilation error
  6. sourceList.add(4)
  7. println(referenceList) // shows the current state of sourceList
  8. //sampleEnd
  9. }

Invoking functions on other collections

Collections can be created in result of various operations on other collections. For example, filtering a list creates a new list of elements that match the filter:

  1. fun main() {
  2. //sampleStart
  3. val numbers = listOf("one", "two", "three", "four")
  4. val longerThan3 = numbers.filter { it.length > 3 }
  5. println(longerThan3)
  6. //sampleEnd
  7. }

Mapping produces a list of a transformation results:

  1. fun main() {
  2. //sampleStart
  3. val numbers = setOf(1, 2, 3)
  4. println(numbers.map { it * 3 })
  5. println(numbers.mapIndexed { idx, value -> value * idx })
  6. //sampleEnd
  7. }

Association produces maps:

  1. fun main() {
  2. //sampleStart
  3. val numbers = listOf("one", "two", "three", "four")
  4. println(numbers.associateWith { it.length })
  5. //sampleEnd
  6. }

For more information about operations on collections in Kotlin, see Collection Operations Overview.