Skip to content

Kotlin kotlin.collections.List API

Kotlin's List<T> — an immutable ordered collection; MutableList<T> adds in-place mutation.

1 class · 8 methods

List<T>

8 methods

A generic ordered collection of elements. List is read-only; MutableList supports modification.

List.size: Int

Returns the number of elements in this collection.

Returns

Int

Example

kotlin
val list = listOf(1, 2, 3)
println(list.size)  // 3
MutableList.add(element: E): Boolean

Adds the specified element to the end of this list. Returns true.

Parameters

NameTypeDescription
elementEElement to add.

Returns

Boolean

Example

kotlin
val list = mutableListOf(1, 2)
list.add(3)
// list == [1, 2, 3]
MutableList.remove(element: E): Boolean

Removes the first occurrence of the specified element. Returns true if removed.

Parameters

NameTypeDescription
elementEElement to remove.

Returns

Boolean

Example

kotlin
val list = mutableListOf(1, 2, 3)
val ok = list.remove(2)
// ok == true, list == [1, 3]
List.contains(element: E): Boolean

Returns true if element is found in the collection.

Parameters

NameTypeDescription
elementEElement to check for.

Returns

Boolean

Example

kotlin
val list = listOf(1, 2, 3)
println(list.contains(2))  // true
println(list.contains(9))  // false
List.map { it -> R }: List<R>

Returns a list containing the results of applying transform to each element.

Parameters

NameTypeDescription
transform(E) -> RMapping lambda.

Returns

List<R>

Example

kotlin
val nums = listOf(1, 2, 3)
val squares = nums.map { it * it }
// squares == [1, 4, 9]
List.filter { it -> Boolean }: List<E>

Returns a list containing only elements matching the given predicate.

Parameters

NameTypeDescription
predicate(E) -> BooleanFiltering lambda.

Returns

List<E>

Example

kotlin
val nums = listOf(1, 2, 3, 4)
val evens = nums.filter { it % 2 == 0 }
// evens == [2, 4]
List.sorted(): List<E>

Returns a new list with all elements sorted ascending according to their natural order.

Returns

List<E>

Example

kotlin
val nums = listOf(3, 1, 2)
val sorted = nums.sorted()
// sorted == [1, 2, 3]
val desc = nums.sortedDescending()
// desc == [3, 2, 1]
List.forEach { it -> Unit }

Performs the given action on each element in order.

Parameters

NameTypeDescription
action(E) -> UnitAction lambda.

Returns

Unit

Example

kotlin
listOf(1, 2, 3).forEach { println(it) }
// prints:
// 1
// 2
// 3