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


当前回答

在Java中没有获得列表的最后一个元素的优雅方法(与Python中的items[-1]相比)。

你必须使用list.get(list.size()-1)。

当处理由复杂方法调用获得的列表时,解决方法在于临时变量:

List<E> list = someObject.someMethod(someArgument, anotherObject.anotherMethod());
return list.get(list.size()-1);

这是避免丑陋且昂贵甚至无法工作的版本的唯一选择:

return someObject.someMethod(someArgument, anotherObject.anotherMethod()).get(
    someObject.someMethod(someArgument, anotherObject.anotherMethod()).size() - 1
);

如果能在Java API中引入对这个设计缺陷的修复,那就太好了。

其他回答

这应该做到:

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

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

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

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

如果您有一个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)用于断言。

你所需要做的就是使用size()来获取数组列表的最后一个值。 例如,如果你是整数的数组列表,那么为了得到最后一个值,你必须

int lastValue = arrList.get(arrList.size()-1);

记住,数组列表中的元素可以通过下标值访问。因此,数组列表通常用于搜索项。

在普通Java中没有优雅的方法。

谷歌番石榴

谷歌番石榴库是伟大的-检查他们的Iterables类。如果列表为空,这个方法将抛出NoSuchElementException,而不是IndexOutOfBoundsException,就像典型的size()-1方法一样-我发现NoSuchElementException更好,或者能够指定默认值:

lastElement = Iterables.getLast(iterableList);

如果列表为空,你也可以提供一个默认值,而不是一个异常:

lastElement = Iterables.getLast(iterableList, null);

或者,如果你使用选项:

lastElementRaw = Iterables.getLast(iterableList, null);
lastElement = (lastElementRaw == null) ? Option.none() : Option.some(lastElementRaw);