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


当前回答

获取数组列表的最后一个值:

var yourlist = ["1","2","3"];
var lastvalue = yourlist[yourlist.length -1];

它给出的输出是3。

其他回答

这应该做到:

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

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

val lastItem = list.last()

下面是List接口的一部分(由ArrayList实现):

E e = list.get(list.size() - 1);

E是元素类型。如果列表为空,get抛出IndexOutOfBoundsException异常。你可以在这里找到完整的API文档。

使用lambdas:

Function<ArrayList<T>, T> getLast = a -> a.get(a.size() - 1);

如果您有一个Spring项目,您也可以使用CollectionUtils。因此,您不需要添加额外的依赖项,如谷歌Guava。

它是空安全的,所以如果你传递null,你只会收到null返回。但是在处理响应时要小心。

下面是一些单元测试来演示它们:

@Test
void lastElementOfList() {
    var names = List.of("John", "Jane");

    var lastName = CollectionUtils.lastElement(names);

    then(lastName)
        .as("Expected Jane to be the last name in the list")
        .isEqualTo("Jane");
}

@Test
void lastElementOfSet() {
    var names = new TreeSet<>(Set.of("Jane", "John", "James"));

    var lastName = CollectionUtils.lastElement(names);

    then(lastName)
        .as("Expected John to be the last name in the list")
        .isEqualTo("John");
}

注意:org.assertj.core.api.BDDAssertions#then(java.lang.String)用于断言。