Как получить последнее значение ArrayList - PullRequest
515 голосов
/ 27 марта 2009

Как я могу получить последнее значение ArrayList?

Я не знаю последний индекс ArrayList.

Ответы [ 16 ]

595 голосов
/ 27 марта 2009

Следующее является частью интерфейса List (который реализует ArrayList):

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

E - тип элемента. Если список пуст, get выдает IndexOutOfBoundsException. Вы можете найти всю документацию по API здесь .

185 голосов
/ 28 декабря 2012

В ванильной Java нет элегантного пути.

Google Guava

Библиотека Google Guava великолепна - посмотрите их 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);
178 голосов
/ 27 марта 2009

это должно сделать это:

if (arrayList != null && !arrayList.isEmpty()) {
  T item = arrayList.get(arrayList.size()-1);
}
26 голосов
/ 10 октября 2014

Я использую класс 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();
  }
}
10 голосов
/ 27 марта 2009

Метод size() возвращает количество элементов в ArrayList. Значения индекса элементов: от 0 до (size()-1), поэтому вы должны использовать myArrayList.get(myArrayList.size()-1) для получения последнего элемента.

5 голосов
/ 08 мая 2018

Использование лямбд:

Function<ArrayList<T>, T> getLast = a -> a.get(a.size() - 1);
4 голосов
/ 12 декабря 2014

Если можете, замените ArrayList на ArrayDeque, который имеет удобные методы, такие как removeLast.

1 голос
/ 09 апреля 2019

Как указано в решении, если 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;
0 голосов
/ 06 июня 2019

Не существует элегантного способа получения последнего элемента списка в Java (по сравнению, например, с items[-1] в Python).

Вы должны использовать 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.

0 голосов
/ 04 декабря 2018

Альтернатива с использованием Stream API:

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

Результат в дополнительном элементе последнего элемента.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...