Reputation: 387
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?
Upvotes: 6
Views: 7219
Reputation: 1
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.
Upvotes: 0
Reputation: 453
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)
Upvotes: 1
Reputation: 1227
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.
Upvotes: 0
Reputation: 153
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]
Upvotes: 1
Reputation: 11
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
Upvotes: -1
Reputation: 387
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
Upvotes: 1