如何获取数组列表的最后一个值?


当前回答

在Kotlin中,你可以使用最后的方法:

val lastItem = list.last()

其他回答

guava提供了另一种从List中获取最后一个元素的方法:

last = Lists.reverse(list).get(0)

如果提供的列表为空,则抛出IndexOutOfBoundsException异常

这应该做到:

if (arrayList != null && !arrayList.isEmpty()) {
  T item = arrayList.get(arrayList.size()-1);
}

在Kotlin中,你可以使用最后的方法:

val lastItem = list.last()

如果修改列表,则使用listIterator()并从最后一个索引(即分别为size()-1)开始迭代。 如果你再次失败,检查你的列表结构。

使用流API的替代方案:

list.stream().reduce((first, second) -> second)

结果为最后一个元素的Optional。