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


当前回答

考虑空列表的一行代码如下:

T lastItem = list.size() == 0 ? null : list.get(list.size() - 1);

或者如果你不喜欢空值(性能不是问题):

Optional<T> lastItem = list.stream().reduce((first, second) -> second);

其他回答

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

如果可以的话,将ArrayList替换为ArrayDeque,它有方便的方法,如removeLast。

这应该做到:

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

这对我很管用。

private ArrayList<String> meals;
public String take(){
  return meals.remove(meals.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);