简体   繁体   English

如何获取 ArrayList 的最后一个值

[英]How to get the last value of an ArrayList

How can I get the last value of an ArrayList?如何获取 ArrayList 的最后一个值?

The following is part of theList interface (which ArrayList implements):以下是List接口的一部分(由 ArrayList 实现):

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

E is the element type. E是元素类型。 If the list is empty, get throws an IndexOutOfBoundsException .如果列表为空,则get抛出IndexOutOfBoundsException You can find the whole API documentation here .您可以在此处找到整个 API 文档。

There isn't an elegant way in vanilla Java.在香草 Java 中没有优雅的方式。

Google Guava谷歌番石榴

The Google Guava library is great - check out their Iterables class . Google Guava库很棒 - 查看他们的Iterables This method will throw a NoSuchElementException if the list is empty, as opposed to an IndexOutOfBoundsException , as with the typical size()-1 approach - I find a NoSuchElementException much nicer, or the ability to specify a default:如果列表为空,则此方法将抛出NoSuchElementException ,而不是IndexOutOfBoundsException ,就像典型的size()-1方法一样 - 我发现NoSuchElementException更好,或者能够指定默认值:

lastElement = Iterables.getLast(iterableList);

You can also provide a default value if the list is empty, instead of an exception:如果列表为空,您还可以提供默认值,而不是异常:

lastElement = Iterables.getLast(iterableList, null);

or, if you're using Options:或者,如果您使用的是选项:

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

this should do it:这应该这样做:

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

I use micro-util class for getting last (and first) element of list:我使用 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;
    }
}

Slightly more flexible:稍微灵活一点:

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();
  }
}

The size() method returns the number of elements in the ArrayList. size()方法返回 ArrayList 中元素的数量。 The index values of the elements are 0 through (size()-1) , so you would use myArrayList.get(myArrayList.size()-1) to retrieve the last element.元素的索引值为0(size()-1) ,因此您将使用myArrayList.get(myArrayList.size()-1)来检索最后一个元素。

There is no elegant way of getting the last element of a list in Java (compared to eg items[-1] in Python).在 Java 中没有获得列表最后一个元素的优雅方法(与 Python 中的例如items[-1]相比)。

You have to use list.get(list.size()-1) .您必须使用list.get(list.size()-1)

When working with lists obtained by complicated method calls, the workaround lies in temporary variable:处理通过复杂方法调用获得的列表时,解决方法在于临时变量:

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

This is the only option to avoid ugly and often expensive or even not working version:这是避免丑陋且通常昂贵甚至无法工作的版本的唯一选择:

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

It would be nice if fix for this design flaw was introduced to Java API.如果将此设计缺陷的修复引入 Java API,那就太好了。

使用 lambda 表达式:

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

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

If you use a LinkedList instead , you can access the first element and the last one with just getFirst() and getLast() (if you want a cleaner way than size() -1 and get(0))如果您使用 LinkedList ,则可以仅使用getFirst()getLast()访问第一个元素和最后一个getLast() (如果您想要比 size() -1 和 get(0) 更简洁的方法)

Implementation执行

Declare a LinkedList声明一个链表

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

Then this are the methods you can use to get what you want, in this case we are talking about FIRST and LAST element of a list那么这就是你可以用来获得你想要的东西的方法,在这种情况下,我们谈论的是列表的第一个最后一个元素

/**
     * 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);
    }

So , then you can use所以,那么你可以使用

mLinkedList.getLast(); 

to get the last element of the list.获取列表的最后一个元素。

As stated in the solution, if the List is empty then an IndexOutOfBoundsException is thrown.如解决方案中所述,如果List为空,则抛出IndexOutOfBoundsException A better solution is to use the Optional type:更好的解决方案是使用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));
    }
}

As you'd expect, the last element of the list is returned as an Optional :如您所料,列表的最后一个元素作为Optional返回:

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

It also deals gracefully with empty lists as well:它还可以优雅地处理空列表:

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

In case you have a spring project, you can also use the CollectionUtils.lastElement from Spring ( javadoc ) and you don't need to add an extra dependency like Google Guave if you didn't need to before.如果您有一个 spring 项目,您还可以使用 Spring ( javadoc ) 中的CollectionUtils.lastElement如果您之前不需要,则不需要添加像 Google Guave 这样的额外依赖项。

It is null-safe so if you pass null, you will simply receive null in return.它是空安全的,所以如果你传递空值,你只会收到空值作为回报。 Be careful when handling the response though.但是在处理响应时要小心。

Here are somes unit test to demonstrate them:下面是一些单元测试来演示它们:

@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");
}

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

A one liner that takes into account empty lists would be:考虑到空列表的单班轮将是:

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

Or if you don't like null values (and performance isn't an issue):或者,如果您不喜欢空值(并且性能不是问题):

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

Since the indexing in ArrayList starts from 0 and ends one place before the actual size hence the correct statement to return the last arraylist element would be:由于 ArrayList 中的索引从 0 开始并在实际大小前一个位置结束,因此返回最后一个 arraylist 元素的正确语句是:

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

For example:例如:

if size of array list is 5, then size-1 = 4 would return the last array element.如果数组列表的大小为 5,则 size-1 = 4 将返回最后一个数组元素。

guava provides another way to obtain the last element from a List :番石榴提供了另一种从List获取最后一个元素的方法:

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

if the provided list is empty it throws an IndexOutOfBoundsException如果提供的列表为空,则抛出IndexOutOfBoundsException

This worked for me.这对我有用。

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

To Get the last value of arraylist in JavaScript :在 JavaScript 中获取 arraylist 的最后一个值:

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

It gives the output as 3 .它给出的输出为 3 。

The last item in the list is list.size() - 1 .列表中的最后一项是list.size() - 1 The collection is backed by an array and arrays start at index 0.该集合由一个数组支持,数组从索引 0 开始。

So element 1 in the list is at index 0 in the array所以列表中的元素 1 位于数组中的索引 0

Element 2 in the list is at index 1 in the array列表中的元素 2 位于数组中的索引 1

Element 3 in the list is at index 2 in the array列表中的元素 3 位于数组中的索引 2

and so on..等等..

How about this.. Somewhere in your class...这个怎么样..在你班级的某个地方......

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;
    }

If you modify your list, then use listIterator() and iterate from last index (that is size()-1 respectively).如果您修改列表,则使用listIterator()并从最后一个索引(即分别为size()-1 )进行迭代。 If you fail again, check your list structure.如果您再次失败,请检查您的列表结构。

All you need to do is use size() to get the last value of the Arraylist.您需要做的就是使用 size() 来获取 Arraylist 的最后一个值。 For ex.例如。 if you ArrayList of integers, then to get last value you will have to如果您是整数的 ArrayList,那么要获得最后一个值,您将不得不

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

Remember, elements in an Arraylist can be accessed using index values.请记住,可以使用索引值访问 Arraylist 中的元素。 Therefore, ArrayLists are generally used to search items.因此,ArrayLists 通常用于搜索项目。

arrays store their size in a local variable called 'length'.数组将其大小存储在名为“length”的局部变量中。 Given an array named "a" you could use the following to reference the last index without knowing the index value给定一个名为“a”的数组,您可以使用以下内容在不知道索引值的情况下引用最后一个索引

a[a.length-1] a[a.length-1]

to assign a value of 5 to this last index you would use:将值 5 分配给最后一个索引,您将使用:

a[a.length-1]=5; a[a.length-1]=5;

Alternative using the Stream API:使用 Stream API 的替代方法:

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

Results in an Optional of the last element.结果是最后一个元素的 Optional。

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

val lastItem = list.last()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM