Retrieve last item from a List in Kotlin
This article explores different ways to retrieve the last item from a List in Kotlin.
1. Using last() function
A simple and concise solution is to use the last() library function, which returns the last element from the list. It can be used as follows:
|
1 2 3 4 5 |
fun main() { val chars = ('A'..'Z').toList() val lastItem = chars.last() println(lastItem) // 'Z' } |
This, however, throws a java.util.NoSuchElementException if the list is empty. To handle it, you can use the lastOrNull() library function which returns the last element, or null if the list is empty.
|
1 2 3 4 5 |
fun main() { val chars = listOf<Char>() val lastItem = chars.lastOrNull() println(lastItem) // 'Z' } |
2. Using lastIndex property
Another solution to retrieve the last element is using the expression L.get(L.lastIndex). Here L is our list and lastIndex returns the index of the last item in the list.
|
1 2 3 4 5 |
fun main() { val chars = ('A'..'Z').toList() val lastItem = chars[chars.lastIndex] println(lastItem) // 'Z' } |
To handle the java.util.IndexOutOfBoundsException when the list is empty, place a boundary check on the list before accessing the last index.
|
1 2 3 4 5 6 7 8 9 10 11 |
fun <T> getLast(list: List<T>?): T? { return if (list != null && !list.isEmpty()) { list[list.lastIndex] } else null } fun main() { val chars = ('A'..'Z').toList() val lastItem = getLast(chars) println(lastItem) // 'Z' } |
3. Using takeLast() function
If you need to retrieve the last few elements from the list, the recommended solution is to call the takeLast() library function. Note that it returns a list.
|
1 2 3 4 5 |
fun main() { val chars = ('A'..'Z').toList() val newList = chars.takeLast(1) println(newList) // [Z] } |
To “remove” the last few elements from the list and get the remaining elements, use the dropLast() library function.
|
1 2 3 4 5 |
fun main() { val chars = ('A'..'E').toList() val newList = chars.dropLast(1) println(newList) // [A, B, C, D] } |
4. Using Loop
Finally, you can simply iterate through the array and return the last element. However, this is a very inefficient approach to use for an index-based ordered list.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
fun <T> getLast(list: List<T>): T? { var lastItem: T? = null for (e in list) { lastItem = e } return lastItem } fun main() { val chars = ('A'..'Z').toList() val lastItem = getLast(chars) println(lastItem) // 'Z' } |
That’s all about retrieving the last item from a List in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)