List<T>
8 methodsA generic ordered collection of elements. List is read-only; MutableList supports modification.
List.size: IntReturns the number of elements in this collection.
Returns
Int
Example
val list = listOf(1, 2, 3)
println(list.size) // 3MutableList.add(element: E): BooleanAdds the specified element to the end of this list. Returns true.
Parameters
| Name | Type | Description |
|---|---|---|
| element | E | Element to add. |
Returns
Boolean
Example
val list = mutableListOf(1, 2)
list.add(3)
// list == [1, 2, 3]MutableList.remove(element: E): BooleanRemoves the first occurrence of the specified element. Returns true if removed.
Parameters
| Name | Type | Description |
|---|---|---|
| element | E | Element to remove. |
Returns
Boolean
Example
val list = mutableListOf(1, 2, 3)
val ok = list.remove(2)
// ok == true, list == [1, 3]List.contains(element: E): BooleanReturns true if element is found in the collection.
Parameters
| Name | Type | Description |
|---|---|---|
| element | E | Element to check for. |
Returns
Boolean
Example
val list = listOf(1, 2, 3)
println(list.contains(2)) // true
println(list.contains(9)) // falseList.map { it -> R }: List<R>Returns a list containing the results of applying transform to each element.
Parameters
| Name | Type | Description |
|---|---|---|
| transform | (E) -> R | Mapping lambda. |
Returns
List<R>
Example
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
| Name | Type | Description |
|---|---|---|
| predicate | (E) -> Boolean | Filtering lambda. |
Returns
List<E>
Example
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
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
| Name | Type | Description |
|---|---|---|
| action | (E) -> Unit | Action lambda. |
Returns
Unit
Example
listOf(1, 2, 3).forEach { println(it) }
// prints:
// 1
// 2
// 3