Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!

Create an Empty List

listOf < Int > ()
[]
List(0, {0})
[]

Create a List with Initial Values

val list = listOf(0, 1, 2, 3, 4)
list
[0, 1, 2, 3, 4]

Concatenate List with Other Iterables

listOf(0, 1, 2) + listOf(3, 4, 5)
[0, 1, 2, 3, 4, 5]
listOf(0, 1, 2) + mutableListOf(3, 4, 5)
[0, 1, 2, 3, 4, 5]

Sort a List

sorted

If elements in a List implements the Comparable interface, you can call the method sorted to return a sorted List (in nature order).

Note: Pair in Kotin does not implement the Comparable interface!!!

listOf(5, 9, 3, 2).sorted()
[2, 3, 5, 9]
val listPairs = listOf(Pair(5, 7), Pair(5, 3), Pair(1, 2), Pair(2, 3), Pair(1, 9))
listPairs
[(5, 7), (5, 3), (1, 2), (2, 3), (1, 9)]
listPairs.sorted()
error: type parameter bound for T in fun <T : Comparable<T>> Iterable<T>.sorted(): List<T>
 is not satisfied: inferred type Pair<Int, Int> is not a subtype of Comparable<Pair<Int, Int>>
listPairs.sorted()
          ^

sortedBy

listPairs.sortedBy{ it.first }
[(1, 2), (1, 9), (2, 3), (5, 7), (5, 3)]

sortedWith

listPairs.sortedWith(compareBy({it.first}, {it.second}))
[(1, 2), (1, 9), (2, 3), (5, 3), (5, 7)]

Methods and Operators

listOf(1, 2, 3).joinToString(", ")
1, 2, 3
list.subList(1, 3)
[1, 2]
list.take(3)
[0, 1, 2]
list.takeLast(2)
[3, 4]

data class is preferred over Tuple-like data.

ceil(2.3)
3.0