Create an Empty List¶
In [1]:
listOf < Int > ()
Out[1]:
In [2]:
List(0, {0})
Out[2]:
Create a List with Initial Values¶
In [9]:
val list = listOf(0, 1, 2, 3, 4)
list
Out[9]:
Concatenate List with Other Iterables¶
In [2]:
listOf(0, 1, 2) + listOf(3, 4, 5)
Out[2]:
In [3]:
listOf(0, 1, 2) + mutableListOf(3, 4, 5)
Out[3]:
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!!!
In [7]:
listOf(5, 9, 3, 2).sorted()
Out[7]:
In [2]:
val listPairs = listOf(Pair(5, 7), Pair(5, 3), Pair(1, 2), Pair(2, 3), Pair(1, 9))
listPairs
Out[2]:
In [4]:
listPairs.sorted()
sortedBy¶
In [7]:
listPairs.sortedBy{ it.first }
Out[7]:
sortedWith¶
In [5]:
listPairs.sortedWith(compareBy({it.first}, {it.second}))
Out[5]:
Methods and Operators¶
In [6]:
listOf(1, 2, 3).joinToString(", ")
Out[6]:
In [12]:
list.subList(1, 3)
Out[12]:
In [10]:
list.take(3)
Out[10]:
In [11]:
list.takeLast(2)
Out[11]:
data class is preferred over Tuple-like data.
In [3]:
ceil(2.3)
Out[3]:
References¶
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-mutable-list.html
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/mutable-list-of.html
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-list/index.html
https://stackoverflow.com/questions/33640864/how-to-sort-based-on-compare-multiple-values-in-kotlin
In [ ]: