ChatGPT解决这个技术问题 Extra ChatGPT

如何获取 ArrayList 的最后一个值

如何获取 ArrayList 的最后一个值?

我赞成这个问题,因为我想知道为什么没有这样的方法: getLastItem() 并来看看是否有答案。 list.size() - 1 不漂亮。
@NunoGonçalves 你总是可以继承它!
您始终可以使用具有方法 getLast() 的 LinkedList
链接列表增加了一大堆开销。使用 Guava 如下所示: lastElement = Iterables.getLast(iterableList);或者简单地用 size() - 1 索引一个 get() 调用。与不需要时使用链表相比,它并不难看。通常的警告适用于异常条件 - 请参阅 ArrayList javadoc。
使用 list.size() -1 并不漂亮,但为此使用 3rd 方 API 更糟

J
Jarvis

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

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

E 是元素类型。如果列表为空,get 会抛出 IndexOutOfBoundsException。您可以找到整个 API 文档 here


这会导致列表的迭代吗?这对我来说似乎不是很有效。我来自 C++,在列表对象上有实际的 front() 和 back() 方法,它们在内部使用 head 和 tail 引用实现。 Java中是否有类似的机制?
不会工作。如果列表为空,list.size() 将返回 0,你会得到 list.get(-1);
@feresr 嗯。他想获得列表中的最后一个值。当然,这意味着 size() > 0。对于任何类型的实现都是如此。通读到底可以节省您写评论所需的时间和我回答的时间:) 我的回答最后说“如果列表为空,get throws an IndexOutOfBoundsException”
@Brady 它不会导致 ArrayList 的 O(n) 迭代,因为您可以猜到,它由数组支持。因此,简单的 get() 只会导致从数组中进行恒定时间的检索。 (JDK 源证实了这一点)对于其他列表实现,这不能保证,例如,LinkedList 有一个 getLast() 方法,它是恒定时间的。
我不明白他们为什么决定为他们的 Vector 而不是为 ArrayList 实现一个简单的 lastElement() 方法。这种不一致是怎么回事?
O
Olivier Grégoire

香草 Java 中没有优雅的方式。

谷歌番石榴

Google Guava 库很棒 - 看看他们的 Iterables class。如果列表为空,则此方法将抛出 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);

你知道这个方法是否对列表进行线性遍历以找到最后一个元素?
@BillMan 在 HashSet 的情况下是的,在 ArrayList 的情况下没有。
您应该添加 Iterables.getLast 检查 RandomAccess 是否已实现,因此它是否访问 O(1) 中的项目。
您可以使用本机 Java Optional 而不是 Option。它也会更干净一点:lastElement = Optional.ofNullable(lastElementRaw);
C
Christian

这应该这样做:

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

没有时尚的方法吗? :/
您可能至少应该演示分配它... ArrayList.get 没有副作用。
表明上面没有分配/返回任何东西是不是太小气了?
如果 ArrayList 只有一条记录,则发生异常。解决方案是什么?
@hasnain_ahmad,当 ArraList 有 1 个元素时它可以正常工作,您应该担心未初始化的 ArrayList 和 ArrayList 的记录为零。这个答案处理了这两种情况
D
Dave Jarvis

我使用 micro-util 类来获取列表的最后一个(也是第一个)元素:

public final class Lists {

    private Lists() {
    }

    public static <T> T getFirst(List<T> list) {
        return list != null && !list.isEmpty() ? list.get(0) : null;
    }

    public static <T> T getLast(List<T> list) {
        return list != null && !list.isEmpty() ? list.get(list.size() - 1) : null;
    }
}

稍微灵活一点:

import java.util.List;

/**
 * Convenience class that provides a clearer API for obtaining list elements.
 */
public final class Lists {

  private Lists() {
  }

  /**
   * Returns the first item in the given list, or null if not found.
   *
   * @param <T> The generic list type.
   * @param list The list that may have a first item.
   *
   * @return null if the list is null or there is no first item.
   */
  public static <T> T getFirst( final List<T> list ) {
    return getFirst( list, null );
  }

  /**
   * Returns the last item in the given list, or null if not found.
   *
   * @param <T> The generic list type.
   * @param list The list that may have a last item.
   *
   * @return null if the list is null or there is no last item.
   */
  public static <T> T getLast( final List<T> list ) {
    return getLast( list, null );
  }

  /**
   * Returns the first item in the given list, or t if not found.
   *
   * @param <T> The generic list type.
   * @param list The list that may have a first item.
   * @param t The default return value.
   *
   * @return null if the list is null or there is no first item.
   */
  public static <T> T getFirst( final List<T> list, final T t ) {
    return isEmpty( list ) ? t : list.get( 0 );
  }

  /**
   * Returns the last item in the given list, or t if not found.
   *
   * @param <T> The generic list type.
   * @param list The list that may have a last item.
   * @param t The default return value.
   *
   * @return null if the list is null or there is no last item.
   */
  public static <T> T getLast( final List<T> list, final T t ) {
    return isEmpty( list ) ? t : list.get( list.size() - 1 );
  }

  /**
   * Returns true if the given list is null or empty.
   *
   * @param <T> The generic list type.
   * @param list The list that has a last item.
   *
   * @return true The list is empty.
   */
  public static <T> boolean isEmpty( final List<T> list ) {
    return list == null || list.isEmpty();
  }
}

只需使用番石榴。不要重新发明
@ClickUpvote 仅将番石榴用于一种微小的方法在许多情况下都是矫枉过正的。我的答案是为寻找普通 Java 解决方案的人准备的。如果您已经在项目中使用 Guava,请参阅基于 Guava 的解决方案的其他答案。
如果你不使用番石榴,你最终会编写很多这样的实用程序类。
有时,获得添加第三方库的权限可能比添加单个本地 Java 类要复杂得多。例如,政府合同限制和筛选第三方图书馆。
isEmpty 不检查列表是否为空,因此应为 isNullOrEmpty,这不是问题的一部分 - 您尝试增强答案集或为您提供实用程序类(这是一种重新发明) .
K
Ken Paul

size() 方法返回 ArrayList 中的元素数。元素的索引值为 0(size()-1),因此您将使用 myArrayList.get(myArrayList.size()-1) 检索最后一个元素。


T
Tregoreg

在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,那就太好了。


我在这里没有看到“设计缺陷”,您提出的是一个不值得添加到 List 界面的罕见用例。如果您只对最后一个元素感兴趣,为什么要调用返回列表的方法?我不记得我以前见过。
@DorianGray 从列表中读取最后一个元素是一种非常常见的操作,list.get(list.size()-1) 是显示该问题的最小示例。我同意“高级”示例可能会引起争议,并且可能是边缘案例,我只是想展示该问题如何进一步传播。假设 someObject 的类是外来的,来自外部库。
我看不出这在哪里很常见,如果是,您最好改用 ArrayDeque
@DorianGray 这个问题有很多赞成和意见,所以有很多人有兴趣获得 ArrayList 的最后一个值。
L
Luis Vieira Damiani

使用 lambda:

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

J
John Glassmyer

如果可以,请将 ArrayList 换成 ArrayDeque,它具有像 removeLast 这样的便捷方法。


这意味着与直接访问的恒定成本相比,至少是线性成本,但值得一提。
@KarlRichter 是的。这与 ArrayDeque 的接口中缺少 get(int) 等方法相对应。这就是我的“如果可以”的意思;如果列表没有被索引访问,那么它可能不需要是一个列表。
C
Colin Breame

如解决方案中所述,如果 List 为空,则抛出 IndexOutOfBoundsException。更好的解决方案是使用 Optional 类型:

public class ListUtils {
    public static <T> Optional<T> last(List<T> list) {
        return list.isEmpty() ? Optional.empty() : Optional.of(list.get(list.size() - 1));
    }
}

如您所料,列表的最后一个元素作为 Optional 返回:

var list = List.of(10, 20, 30);
assert ListUtils.last(list).orElse(-1) == 30;

它还可以优雅地处理空列表:

var emptyList = List.<Integer>of();
assert ListUtils.last(emptyList).orElse(-1) == -1;

G
Gastón Saillén

如果您改用 LinkedList,则可以仅使用 getFirst()getLast() 访问第一个元素和最后一个元素(如果您想要比 size() -1 和 get(0) 更简洁的方式)

执行

声明一个链表

LinkedList<Object> mLinkedList = new LinkedList<>();

然后这是您可以用来获得所需内容的方法,在这种情况下,我们正在讨论列表的 FIRST 和 LAST 元素

/**
     * Returns the first element in this list.
     *
     * @return the first element in this list
     * @throws NoSuchElementException if this list is empty
     */
    public E getFirst() {
        final Node<E> f = first;
        if (f == null)
            throw new NoSuchElementException();
        return f.item;
    }

    /**
     * Returns the last element in this list.
     *
     * @return the last element in this list
     * @throws NoSuchElementException if this list is empty
     */
    public E getLast() {
        final Node<E> l = last;
        if (l == null)
            throw new NoSuchElementException();
        return l.item;
    }

    /**
     * Removes and returns the first element from this list.
     *
     * @return the first element from this list
     * @throws NoSuchElementException if this list is empty
     */
    public E removeFirst() {
        final Node<E> f = first;
        if (f == null)
            throw new NoSuchElementException();
        return unlinkFirst(f);
    }

    /**
     * Removes and returns the last element from this list.
     *
     * @return the last element from this list
     * @throws NoSuchElementException if this list is empty
     */
    public E removeLast() {
        final Node<E> l = last;
        if (l == null)
            throw new NoSuchElementException();
        return unlinkLast(l);
    }

    /**
     * Inserts the specified element at the beginning of this list.
     *
     * @param e the element to add
     */
    public void addFirst(E e) {
        linkFirst(e);
    }

    /**
     * Appends the specified element to the end of this list.
     *
     * <p>This method is equivalent to {@link #add}.
     *
     * @param e the element to add
     */
    public void addLast(E e) {
        linkLast(e);
    }

所以,那么你可以使用

mLinkedList.getLast(); 

获取列表的最后一个元素。


最好的回应在这里!
C
Craigo

考虑到空列表的一个班轮将是:

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

或者,如果您不喜欢 null 值(并且性能不是问题):

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

J
Jacob van Lingen

如果您有一个 Spring 项目,您还可以使用 Spring (javadoc) 中的 CollectionUtils.lastElement,因此您不需要像 Google Guava 这样添加额外的依赖项。

它是 null 安全的,因此如果您传递 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) 用于断言。


s
shravyaverma

由于 ArrayList 中的索引从 0 开始并在实际大小前一位结束,因此返回最后一个 arraylist 元素的正确语句将是:

int last = mylist.get(mylist.size()-1);

例如:

如果数组列表的大小为 5,则 size-1 = 4 将返回最后一个数组元素。


p
pero_hero

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

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

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


java.util.Collections#reverse 也这样做。
@RoBeaToZ,确实如此,但它通过迭代更改原始列表并返回 void,因此它认为不适合此目的。
仅获得一个元素就相当昂贵。想象一下,您的列表有 1.000.000 个左右的条目。
@philburns 无论列表大小如何,此调用都在 O(1) 中
M
Med Sep

这对我有用。

private ArrayList<String> meals;
public String take(){
  return meals.remove(meals.size()-1);
}

M
MircoProgram

列表中的最后一项是 list.size() - 1。该集合由一个数组支持,数组从索引 0 开始。

所以列表中的元素 1 位于数组中的索引 0

列表中的元素 2 在数组中的索引 1 处

列表中的元素 3 在数组中的索引 2 处

等等..


@JohannesSchaub 之前的回答没有附加价值
r
rokrfellr

这个怎么样..在你班上的某个地方......

List<E> list = new ArrayList<E>();
private int i = -1;
    public void addObjToList(E elt){
        i++;
        list.add(elt);
    }


    public E getObjFromList(){
        if(i == -1){ 
            //If list is empty handle the way you would like to... I am returning a null object
            return null; // or throw an exception
        }

        E object = list.get(i);
        list.remove(i); //Optional - makes list work like a stack
        i--;            //Optional - makes list work like a stack
        return object;
    }

B
Bernhard Barker

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


U
Undo

您需要做的就是使用 size() 来获取 Arraylist 的最后一个值。例如。如果你是整数的 ArrayList,那么要获得最后一个值,你将不得不

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

请记住,可以使用索引值访问 Arraylist 中的元素。因此,ArrayLists 一般用于搜索项目。


@JohannesSchaub 之前的回答没有附加价值
c
closeab

数组将它们的大小存储在一个名为“length”的局部变量中。给定一个名为“a”的数组,您可以使用以下内容来引用最后一个索引而不知道索引值

a[a.length-1]

要将值 5 分配给最后一个索引,您将使用:

a[a.length-1]=5;


这是一个 ArrayList 而不是一个数组。
P
Prasoon Mishra

在 JavaScript 中获取 arraylist 的最后一个值:

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

它给出的输出为 3 。


T
Terran

使用 Stream API 的替代方法:

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

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


O
Ollie

在 Kotlin 中,您可以使用方法 last

val lastItem = list.last()

然而这是java
创建 Kotlin 背后的想法之一是涵盖 Java 令人不舒服的小方面。所以我认为推荐考虑 Kotlin 是有道理的,至少对于执行数据分析的应用程序部分。