How can I get the second to last item in a Kotlin List?
Asked Answered
W

8

6

Let's say I have a List in Kotlin like:

val lst = MutableList<Int>()

If I want the last item, I can do lst.last(), but what about the second to last?

Whicker answered 14/12, 2019 at 2:28 Comment(0)
S
3

How about:

val secondLast = lst.dropLast(1).last()

:-)

Scott answered 7/3, 2023 at 19:29 Comment(0)
W
1

You can use the size of the list to compute the index of the item you want.

For example, the last item in the list is lst[lst.size - 1].

The second to last item in the list is lst[lst.size - 2].

The third to last item in the list is lst[lst.size - 3].

And so on.

Be sure the list is large enough to have an n'th to last item, otherwise you will get an index error

Whicker answered 14/12, 2019 at 2:28 Comment(0)
E
1

Use Collections Slice

val list = mutableListOf("one" , "two" , "three")
print(list.slice(1..list.size - 1))

This will give you the following result [two, three]

Elyssa answered 4/12, 2021 at 12:25 Comment(0)
T
1

Take secondLast element with null check,

fun <T> List<T>.secondLast(): T {
if (size < 2)
    throw NoSuchElementException("List has less than two elements")
return this[size - 2]}

or use this, It simply return null if the index size does not match

myList.getOrNull(myList.lastIndex - 1)
Transcript answered 12/3, 2022 at 4:0 Comment(0)
M
0

Suppose you have 5 items in your val lst = MutableList<Int>() and you want to access the second last, it means listObject[3](list start with 0th index).

lst.add(101) - 0th Index
lst.add(102) - 1th Index
lst.add(103) - 2th Index
lst.add(104) - 3th Index
lst.add(105) - 4th Index

So you can try this

last[lst.size - 2] = 104 3rd Index 

lst.size return 5, so if you use size - 1 it means you try to access last index 4th one, but when you use size - 2 it means you try to access the second last index 3rd.

Millimicron answered 22/2, 2022 at 5:30 Comment(0)
H
0

Use slice and until in Kotlin.

lst.slice(1 until lst.size)
Halve answered 12/3, 2023 at 23:49 Comment(0)
N
0

You could reverse the list and then just use the index

val secondLast = lst.reversed()[1]

I like the dropLast() approach that Blundell mentioned, but this may be slightly more intuitive.

Neodarwinism answered 10/9, 2024 at 18:45 Comment(0)
G
-1

drop first lst.drop(1)

take from last lst.takeLast(lst.size - 1 )

slice from..to lst.slice(1..(lst.size-1) )

You may refer to this link https://kotlinlang.org/docs/collection-parts.html

Grajeda answered 4/7, 2021 at 7:24 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.