How to get the last value of an ArrayList

JavaArraylist

Java Problem Overview


How can I get the last value of an ArrayList?

Java Solutions


Solution 1 - Java

The following is part of the List interface (which ArrayList implements):

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

E is the element type. If the list is empty, get throws an IndexOutOfBoundsException. You can find the whole API documentation here.

Solution 2 - Java

There isn't an elegant way in vanilla Java.

Google Guava

The Google Guava library is great - check out their Iterables class. 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:

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

Solution 3 - Java

this should do it:

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

Solution 4 - Java

I use micro-util class for getting last (and first) element of list:

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

Solution 5 - Java

The size() method returns the number of elements in the 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.

Solution 6 - Java

Using lambdas:

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

Solution 7 - Java

There is no elegant way of getting the last element of a list in Java (compared to e.g. items[-1] in Python).

You have to use 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.

Solution 8 - Java

If you can, swap out the ArrayList for an ArrayDeque, which has convenient methods like removeLast.

Solution 9 - Java

As stated in the solution, if the List is empty then an IndexOutOfBoundsException is thrown. A better solution is to use the Optional type:

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:

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;

Solution 10 - Java

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))

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.

Solution 11 - Java

In case you have a Spring project, you can also use the CollectionUtils.lastElement from Spring (javadoc), so you don't need to add an extra dependency like Google Guava.

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.

Solution 12 - Java

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

Solution 13 - Java

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:

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.

Solution 14 - Java

guava provides another way to obtain the last element from a List:

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

if the provided list is empty it throws an IndexOutOfBoundsException

Solution 15 - Java

This worked for me.

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

Solution 16 - Java

The last item in the list is list.size() - 1. The collection is backed by an array and arrays start at index 0.

So element 1 in the list is at index 0 in the array

Element 2 in the list is at index 1 in the array

Element 3 in the list is at index 2 in the array

and so on..

Solution 17 - Java

If you modify your list, then use listIterator() and iterate from last index (that is size()-1 respectively). If you fail again, check your list structure.

Solution 18 - Java

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

Solution 19 - Java

All you need to do is use size() to get the last value of the Arraylist. For ex. if you ArrayList of integers, then to get last value you will have to

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

Remember, elements in an Arraylist can be accessed using index values. Therefore, ArrayLists are generally used to search items.

Solution 20 - Java

arrays store their size in a local variable called 'length'. Given an array named "a" you could use the following to reference the last index without knowing the index value

a[a.length-1]

to assign a value of 5 to this last index you would use:

a[a.length-1]=5;

Solution 21 - Java

To Get the last value of arraylist in JavaScript :

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

It gives the output as 3 .

Solution 22 - Java

Alternative using the Stream API:

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

Results in an Optional of the last element.

Solution 23 - Java

In Kotlin, you can use the method last:

val lastItem = list.last()

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJessyView Question on Stackoverflow
Solution 1 - JavaJohannes Schaub - litbView Answer on Stackoverflow
Solution 2 - JavaAntony StubbsView Answer on Stackoverflow
Solution 3 - JavaHenrik PaulView Answer on Stackoverflow
Solution 4 - Javauser11153View Answer on Stackoverflow
Solution 5 - JavaKen PaulView Answer on Stackoverflow
Solution 6 - JavaLuis Vieira DamianiView Answer on Stackoverflow
Solution 7 - JavaTregoregView Answer on Stackoverflow
Solution 8 - JavaJohn GlassmyerView Answer on Stackoverflow
Solution 9 - JavaColin BreameView Answer on Stackoverflow
Solution 10 - JavaGastón SaillénView Answer on Stackoverflow
Solution 11 - JavaBitfullByteView Answer on Stackoverflow
Solution 12 - JavaCraigoView Answer on Stackoverflow
Solution 13 - JavashravyavermaView Answer on Stackoverflow
Solution 14 - Javapero_heroView Answer on Stackoverflow
Solution 15 - JavaMed SepView Answer on Stackoverflow
Solution 16 - JavaMircoProgramView Answer on Stackoverflow
Solution 17 - JavadaeView Answer on Stackoverflow
Solution 18 - JavarokrfellrView Answer on Stackoverflow
Solution 19 - Javauser4660857View Answer on Stackoverflow
Solution 20 - JavacloseabView Answer on Stackoverflow
Solution 21 - JavaPrasoon MishraView Answer on Stackoverflow
Solution 22 - JavaTerranView Answer on Stackoverflow
Solution 23 - JavaOllieView Answer on Stackoverflow