How can I get the last value of an ArrayList?
How can I get the last value of an ArrayList?
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.
this should do it:
if (arrayList != null && !arrayList.isEmpty()) {
T item = arrayList.get(arrayList.size()-1);
}
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.
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.
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))
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. 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;
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.
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:
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.
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
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 :
var yourlist = ["1","2","3"];
var lastvalue = yourlist[yourlist.length -1];
It gives the output as 3 .
Alternative using the Stream API:
list.stream().reduce((first, second) -> second)
Results in an Optional of the last element.