Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Kotlin Collections

Kotlin Collections

Collections are the most widely used data structure in everyday development, and Kotlin redesigned the interface hierarchy on top of the Java Collections Framework.

It splits "read-only" and "mutable" into two sets of interfaces, so a function signature can state clearly "I will not modify this collection", while preserving full interoperability with Java collections.


Collection Hierarchy

Kotlin's collection interfaces are all in the kotlin.collections package, which is imported by default, so no import is needed.

Kotlin collection interface hierarchy: from Iterable to Collection to List and Set, with Map as a separate branch; each read-only and mutable interface is compared through the toMutable family of functions

List and Set belong to the same inheritance chain, while Map is a completely separate branch that does not inherit from Collection nor from Iterable。

Read-only interfaces Mutable interfaces Feature
Iterable MutableIterable The root interface of the collection hierarchy; supports for-loop iteration
Collection MutableCollection Adds size, isEmpty, and contains on top of Iterable
List MutableList Ordered, allows duplicate elements, supports index access
Set MutableSet Elements are unique; repeated additions are ignored
Map MutableMap A collection of key-value pairs with unique keys, independent of Collection

Note:Map is not a Collection. It cannot be used directly in a for loop, nor does it have the size Collection methods beyond that; to iterate it you need to access keys、values or entries。


Read-Only and Mutable Interfaces

Read-only interfaces provide only read methods, with no add、remove、clear modification operations.

Declaring a collection as type List means callers cannot add elements to it; this constraint is enforced by the compiler.

Example

fun main

(

)

{

    val mutable

=

mutableListOf

(

"Runoob"

,

"RUNOOB"

)

   

// The same object, referenced through a read-only interface

    val readOnly

:

List

<

String

=

mutable

// readOnly.add("Kotlin") // Compile error: the List interface has no add method

   

// It can still be modified through a mutable reference

    mutable.

add

(

"Kotlin"

)

   

// The read-only reference sees the same object, so it sees the change too

    println

(

readOnly

)

}

Running result:



[Runoob, RUNOOB, Kotlin]

This shows that a read-only interface constrains "what you can do through this reference", not "this object can never change".


Read-Only Collections Are Not Deeply Immutable

Read-only collections have two often-overlooked boundaries; understanding them can prevent production incidents.

First, a read-only reference may point to a mutable collection; as long as another mutable reference is held, the contents can be changed, as the previous example demonstrated.

Second, the read-only constraint applies only to the collection itself and does not extend recursively to its elements; if an element is a mutable object, it can still be modified.

Example

fun main

(

)

{

   

// The outer list is read-only, but the elements themselves are MutableList

    val users

=

listOf

(

mutableListOf

(

"Runoob"

)

)

   

// users.add(...) is not allowed, but modifying an element is

    users

[

0

]

.

add

(

"RUNOOB"

)

    println

(

users

)

}

Running result:



[[Runoob, RUNOOB]]

Note:If you truly need an immutable collection, you can use kotlinx.collections.immutable persistent collections from the library, or return a copy to callers (such as list.toList()); do not rely on read-only interfaces to guarantee thread safety.


List: Ordered, Allows Duplicates

List is the most commonly used collection; elements are arranged in insertion order, duplicates are allowed, and index-based access is supported.

To create a read-only list, use listOf; to create a mutable list, use mutableListOf or arrayListOf。

Example

fun main

(

)

{

    val readOnly

=

listOf

(

"Runoob"

,

"RUNOOB"

,

"Kotlin"

)

    val mutable

=

mutableListOf

(

"Runoob"

,

"RUNOOB"

)

    val arrayBacked

=

arrayListOf

(

"Runoob"

,

"RUNOOB"

)

    mutable.

add

(

"Kotlin"

)

    arrayBacked.

add

(

"Kotlin"

)

    println

(

readOnly

)

    println

(

mutable

)

    println

(

arrayBacked

)

   

// Index access and several common query methods

    println

(

readOnly

[

0

]

)

    println

(

readOnly.

getOrNull

(

10

)

)

   

// Returns null on an out-of-bounds index instead of throwing an exception

    println

(

readOnly.

indexOf

(

"Kotlin"

)

)

    println

(

readOnly.

contains

(

"RUNOOB"

)

)

}

Running result:



[Runoob, RUNOOB, Kotlin]

[Runoob, RUNOOB, Kotlin]

[Runoob, RUNOOB, Kotlin]

Runoob

null

2

true

mutableListOf and arrayListOf Both return ArrayList on the JVM and are functionally equivalent.

The difference is that arrayListOf has a return type of the concrete ArrayList; choose it when you need to use that type explicitly.


Set: Unique Elements

Set guarantees no duplicate elements; repeated additions do not throw an error, they are simply ignored.

setOf and mutableSetOf On the JVM it is based on LinkedHashSet and preserves insertion order;hashSetOf is based on HashSet and does not guarantee iteration order.

Example

fun main

(

)

{

   

// The duplicate "Runoob" is automatically ignored

    val readOnly

=

setOf

(

"Runoob"

,

"RUNOOB"

,

"Runoob"

)

    val mutable

=

mutableSetOf

(

"Runoob"

,

"RUNOOB"

)

    val hash

=

hashSetOf

(

"Runoob"

,

"RUNOOB"

)

    mutable.

add

(

"Kotlin"

)

    mutable.

add

(

"Runoob"

)

 

// Already present, so it is not added again

    hash.

add

(

"Kotlin"

)

    println

(

readOnly

)

    println

(

mutable

)

    println

(

hash.

sorted

(

)

)

 

// HashSet order is undefined, so sort before printing

    println

(

readOnly.

size

)

    println

(

"RUNOOB"

in readOnly

)

}

Running result:



[Runoob, RUNOOB]

[Runoob, RUNOOB, Kotlin]

[Kotlin, RUNOOB, Runoob]

2

true

Note:Relying on a Set's iteration order is unsafe. When you need a stable order, use setOf、mutableSetOf or linkedSetOf, as both preserve insertion order.


Map: A Collection of Key-Value Pairs

Map stores key-value pairs; keys are unique, while values may be repeated.

To retrieve a value, use bracket syntax map[key]; the return type is V?, and you get null when the key does not exist.

Example

fun main

(

)

{

   

// to is an infix function used to construct key-value pairs

    val readOnly

=

mapOf

(

"Runoob"

to

1

,

"RUNOOB"

to

2

)

    val mutable

=

mutableMapOf

(

"Runoob"

to

1

)

    val hash

=

hashMapOf

(

"Runoob"

to

1

)

    mutable

[

"RUNOOB"

]

=

2

    hash

[

"RUNOOB"

]

=

2

    println

(

readOnly

)

    println

(

mutable

)

    println

(

readOnly

[

"Runoob"

]

)

    println

(

readOnly

[

"Kotlin"

]

)

               

// Returns null when the key does not exist

    println

(

readOnly.

getOrDefault

(

"Kotlin"

,

0

)

)

// Provide a default value

    println

(

readOnly.

keys

)

    println

(

readOnly.

values

)

}

Running result:



{Runoob=1, RUNOOB=2}

{Runoob=1, RUNOOB=2}

1

null

0

[Runoob, RUNOOB]

[1, 2]

When you need to iterate over a Map, use for ((key, value) in map) destructuring syntax.


Comparing Creation Functions

The creation functions have similar names but differ in return type and underlying implementation; choosing the wrong one affects ordering and performance.

function Return Type Underlying JVM Implementation Feature
listOf List Arrays$ArrayList / SingletonList / EmptyList Read-only, ordered, allows duplicates
mutableListOf MutableList ArrayList Supports additions and removals
arrayListOf ArrayList java.util.ArrayList Equivalent to mutableListOf, but returns the concrete type
setOf Set LinkedHashSet Read-only, preserves insertion order
mutableSetOf MutableSet LinkedHashSet Supports additions and removals, preserves insertion order
hashSetOf HashSet java.util.HashSet Does not guarantee iteration order
mapOf Map LinkedHashMap Read-only, preserves insertion order
mutableMapOf MutableMap LinkedHashMap Supports additions and removals, preserves insertion order
hashMapOf HashMap java.util.HashMap Does not guarantee iteration order

Calling with no arguments listOf()、setOf()、mapOf() returns a shared empty collection instance, so creating an empty collection has no extra cost.


Building Collections with a Lambda

List(n) { } creates a list of length n, with the lambda's parameter as the index.

When you need to build dynamically based on conditions, use buildList、buildSet、buildMap, which have been stable since Kotlin 1.6.

Example

fun main

(

)

{

   

// it is the index; generate the squares from 0 to 4

    val squares

=

List

(

5

)

{

it

it

}

    val zeros

=

MutableList

(

3

)

{

0

}

    println

(

squares

)

    println

(

zeros

)

   

// Inside buildList you can write arbitrary logic and finally return a read-only list

    val built

=

buildList

{

        add

(

"Runoob"

)

        add

(

"RUNOOB"

)

       

if

(

size

1

)

add

(

"Kotlin"

)

   

}

    println

(

built

)

    val map

=

buildMap

{

        put

(

"Runoob"

,

1

)

        put

(

"RUNOOB"

,

2

)

   

}

    println

(

map

)

}

Running result:



[0, 1, 4, 9, 16]

[0, 0, 0]

[Runoob, RUNOOB, Kotlin]

{Runoob=1, RUNOOB=2}


Conversions Between Collections

Between read-only and mutable collections, and between different collection types, conversion is done through the toXxx family of functions.

All these functions create a new collection object and leave the original untouched.

Example

fun main

(

)

{

    val numbers

=

listOf

(

3

,

1

,

2

,

1

)

    val set

:

Set

<

Int

=

numbers.

toSet

(

)

           

// Remove duplicates, preserving the order of first occurrence

    val sortedList

:

List

<

Int

=

numbers.

sorted

(

)

 

// Sort and return a new list

    val mutableCopy

:

MutableList

<

Int

=

numbers.

toMutableList

(

)

   

// Modifying the copy does not affect the original list

    mutableCopy.

add

(

99

)

    println

(

numbers

)

    println

(

set

)

    println

(

sortedList

)

    println

(

mutableCopy

)

   

// List Convert to a Map, keeping the last value when a key repeats

    val pairs

=

listOf

(

"Runoob"

to

1

,

"RUNOOB"

to

2

)

    val map

:

Map

<

String

, Int

=

pairs.

toMap

(

)

    println

(

map

)

   

// associate uses lambdas to customize the key and value

    val byLength

=

listOf

(

"Runoob"

,

"Kotlin"

)

.

associate

{

it to it.

length

}

    println

(

byLength

)

}

Running result:



[3, 1, 2, 1]

[3, 1, 2]

[1, 1, 2, 3]

[3, 1, 2, 1, 99]

{Runoob=1, RUNOOB=2}

{Runoob=6, Kotlin=6}

Other commonly used conversion functions include toMutableSet、toMutableMap、toTypedArray, used in the same way as above.


Common questions

List and MutableList What Is the Relationship Between Them?

Both are interfaces,MutableList inheriting from List. The same object can be pointed to by references of both types at once, and what you can do is determined by the reference's static type.

Why map[key] Why Does It Return a Nullable Type?

Because the key may not exist. This is part of the null-safety design: the compiler forces you to handle the "no value" case, and you can use the Elvis operator to provide a default.

listOf Is a Created List Really Immutable?

It cannot be modified through the List interface, but the underlying implementation may be Arrays$ArrayList; if you cast it to MutableList, adding an element will throw a UnsupportedOperationException。

When Should You Use a Set Instead of a List?

Use a Set when you need deduplication or frequent existence checks, because a Set's contains is constant time on average; use a List when you need to preserve order and allow duplicates.