Ben Chuanlong Du's Blog

It is never too late to learn.

List in Kotlin

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]:
[0, 1, 2, 3, 4]

Concatenate List with Other Iterables

In [2]:
listOf(0, 1, 2) + listOf(3, 4, 5)
Out[2]:
[0, 1, 2, 3, 4, 5]
In [3]:
listOf(0, 1, 2) + mutableListOf(3, 4, 5)
Out[3]:
[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!!!

In [7]:
listOf(5, 9, 3, 2).sorted()
Out[7]:
[2, 3, 5, 9]
In [2]:
val listPairs = listOf(Pair(5, 7), Pair(5, 3), Pair(1, 2), Pair(2, 3), Pair(1, 9))
listPairs
Out[2]:
[(5, 7), (5, 3), (1, 2), (2, 3), (1, 9)]
In [4]:
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

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

sortedWith

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

Methods and Operators

In [6]:
listOf(1, 2, 3).joinToString(", ")
Out[6]:
1, 2, 3
In [12]:
list.subList(1, 3)
Out[12]:
[1, 2]
In [10]:
list.take(3)
Out[10]:
[0, 1, 2]
In [11]:
list.takeLast(2)
Out[11]:
[3, 4]

data class is preferred over Tuple-like data.

In [3]:
ceil(2.3)
Out[3]:
3.0
In [ ]:

Comments