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.

Answer from Johannes Schaub - litb on Stack Overflow
🌐
Mkyong
mkyong.com › home › java › java – get the last element of a list
Java – Get the last element of a list | mkyong.com
October 15, 2019 - In Java, index starts at 0, we can get the last index of a list via this formula: list.size() - 1 JavaExample1.java package com.mkyong.test; import java.util.Arrays; import java.util.List; public class
🌐
GeeksforGeeks
geeksforgeeks.org › java › find-first-and-last-element-of-arraylist-in-java
Find first and last element of ArrayList in java - GeeksforGeeks
July 11, 2025 - Get the last element of ArrayList with use of get(index) method by passing index = size - 1. Below is the implementation of the above approach: ... // Java code to find first and last element // of ArrayList import java.util.ArrayList; public ...
🌐
Java Guides
javaguides.net › 2024 › 02 › java-8-program-to-retrieve-last-element-of-list-of-strings.html
Java 8 Program to Retrieve Last Element of a List of Strings
March 12, 2024 - Retrieving the last element of a list is a common operation in software development. With the introduction of Java 8, performing such tasks has become more straightforward thanks to the Stream API.
🌐
Codemia
codemia.io › home › knowledge hub › how to get the last value of an arraylist
How to get the last value of an ArrayList | Codemia
January 25, 2025 - Since ArrayList provides the size() method, which returns the number of elements in the list, and since ArrayList is zero-based index, the last element is at position size() - 1. ... 1import java.util.ArrayList; 2 3public class Main { 4 public static void main(String[] args) { 5 ArrayList<String> ...
🌐
Mkyong
mkyong.com › home › java8 › java 8 – get the last element of a stream?
Java 8 - Get the last element of a Stream? - Mkyong.com
March 14, 2020 - Further Reading: Java 8 Stream.reduce() ... "react", "javascript"); // get last element from a list String result = list.get(list.size() - 1); System.out.println(result); // get last element from a stream, via skip String result2 = ...
🌐
Benchresources
benchresources.net › home › java › java 8 – find first and last elements in a list or arraylist ?
Java 8 – Find First and Last elements in a List or ArrayList ? - BenchResources.Net
June 21, 2022 - Similarly, to get last element from ArrayList, we can use reduce() method of Stream API which returns Optional<T> and · We can invoke get() method on Optional<T> to obtain the final result ... package in.bench.resources.find.list; import java.util.ArrayList; import java.util.List; public class ...
Top answer
1 of 10
285

It is possible to get the last element with the method Stream::reduce. The following listing contains a minimal example for the general case:

Stream<T> stream = ...; // sequential or parallel stream
Optional<T> last = stream.reduce((first, second) -> second);

This implementations works for all ordered streams (including streams created from Lists). For unordered streams it is for obvious reasons unspecified which element will be returned.

The implementation works for both sequential and parallel streams. That might be surprising at first glance, and unfortunately the documentation doesn't state it explicitly. However, it is an important feature of streams, and I try to clarify it:

  • The Javadoc for the method Stream::reduce states, that it "is not constrained to execute sequentially".
  • The Javadoc also requires that the "accumulator function must be an associative, non-interfering, stateless function for combining two values", which is obviously the case for the lambda expression (first, second) -> second.
  • The Javadoc for reduction operations states: "The streams classes have multiple forms of general reduction operations, called reduce() and collect() [..]" and "a properly constructed reduce operation is inherently parallelizable, so long as the function(s) used to process the elements are associative and stateless."

The documentation for the closely related Collectors is even more explicit: "To ensure that sequential and parallel executions produce equivalent results, the collector functions must satisfy an identity and an associativity constraints."


Back to the original question: The following code stores a reference to the last element in the variable last and throws an exception if the stream is empty. The complexity is linear in the length of the stream.

CArea last = data.careas
                 .stream()
                 .filter(c -> c.bbox.orientationHorizontal)
                 .reduce((first, second) -> second).get();
2 of 10
58

If you have a Collection (or more general an Iterable) you can use Google Guava's

Iterables.getLast(myIterable)

as handy oneliner.

Find elsewhere
🌐
Level Up Lunch
leveluplunch.com › java › examples › get-last-element-in-list
Get last element in list | Level Up Lunch
October 16, 2014 - @Test public void get_last_element_in_list_with_java () { List<String> strings = new ArrayList<String>(); strings.add("one"); strings.add("two"); strings.add("three"); String lastElement = null; if (!strings.isEmpty()) { lastElement = strings.get(strings.size() - 1); } assertEquals("three", lastElement); }
🌐
JavaGoal
javagoal.com › home › getlast() method
getlast java - getlast() arraylist to get last element of list
June 6, 2021 - import java.util.LinkedList; public class ExampleOfLinkedList { public static void main(String[] args) { LinkedList<String> listOfNames = new LinkedList<String>(); listOfNames.add("JAVA"); listOfNames.add("GOAL"); listOfNames.add("RAVI"); // It returns the element present at index 1 System.out.println("Element present at last position is = "+listOfNames.getLast()); } }
🌐
Techie Delight
techiedelight.com › home › java › get last value of a list in java
Get last value of a List in Java | Techie Delight
July 7, 2026 - This post will discuss how to get the last value of a List in Java... To retrieve the last element, you can use the expression `L.get(L.size() - 1)` where `L` is your list.
🌐
TutorialsPoint
tutorialspoint.com › article › how-to-find-the-last-occurrence-of-an-element-in-a-java-list
How to find the last occurrence of an element in a Java List?
June 10, 2025 - import java.util.ArrayList; import java.util.List; import java.util.OptionalInt; import java.util.stream.Collectors; import java.util.stream.IntStream; public class LastOccurrenceInList { public static void main(String[] args) { List<Integer> list = new ArrayList<>(); list.add(1); list.add(2); list.add(3); list.add(4); list.add(5); list.add(3); int elementToFind = 3; OptionalInt lastIndex = IntStream.range(0, list.size()) .filter(i -> list.get(i).equals(elementToFind)) .reduce((first, second) -> second); System.out.println("Last occurrence of " + elementToFind + " is at index: " + lastIndex.orElse(-1)); } }
🌐
W3Schools
w3schools.com › java › ref_linkedlist_getlast.asp
Java LinkedList getLast() Method
abs() acos() addExact() asin() atan() atan2() cbrt() ceil() copySign() cos() cosh() decrementExact() exp() expm1() floor() floorDiv() floorMod() getExponent() hypot() IEEEremainder() incrementExact() log() log10() log1p() max() min() multiplyExact() negateExact() nextAfter() nextDown() nextUp() pow() random() rint() round() scalb() signum() sin() sinh() sqrt() subtractExact() tan() tanh() toDegrees() toIntExact() toRadians() ulp() Java Output Methods ... add() addAll() clear() clone() contains ensureCapacity() forEach() get() indexOf() isEmpty() iterator() lastIndexOf() listIterator() remove() removeAll() removeIf() replaceAll() retainAll() set() size() sort() spliterator() subList() toArray() trimToSize() Java LinkedList Methods
🌐
HowToDoInJava
howtodoinjava.com › home › java 8 › getting the last item of a stream
Getting the Last Item of a Stream - Java 8
March 14, 2022 - -1 Exception in thread "main" java.lang.IllegalStateException: no last element at com.howtodoinjava.core.streams.misc.GetLastElement.lambda$1(GetLastElement.java:19) at java.util.Optional.orElseThrow(Unknown Source) at com.howtodoinjava.core.streams.misc.GetLastElement.main(GetLastElement.java:19) Streams.findLast() is really neat, readable, and provides good performance. It returns the last element of the specified stream, or Optional.empty() if the stream is empty. Stream<Integer> stream = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9) .stream(); Integer lastElement = Streams.findLast(stream2).orElse(-1); System.out.println(lastElement); // Prints 9
🌐
javaspring
javaspring.net › blog › java-get-last-element-of-list
Java: Getting the Last Element of a List — javaspring.net
The most basic and widely used method is to use the size() method to calculate the index of the last element. When using this method, always remember to check if the list is empty to avoid exceptions.
🌐
BeginnersBook
beginnersbook.com › 2014 › 10 › how-to-get-the-last-element-of-arraylist
How to get the last element of Arraylist?
September 11, 2022 - There are times when we need to get the last element of an ArrayList, this gets difficult when we don’t know the last index of the list. In this tutorial we are going to see an example to get the last element from ArrayList. import java.util.ArrayList; import java.util.List; public class ArrayListExample { public static void main(String[] args) { /* Creating ArrayList of Strings and adding * elements to it */ List<String> al = new ArrayList<String>(); al.add("Ajay"); al.add("Becky"); al.add("Chaitanya"); al.add("Dimple"); al.add("Rock"); // Displaying ArrayList elements System.out.println("ArrayList contains: "+al); // Logic to get the last element from ArrayList if (al != null && !al.isEmpty()) { System.out.println("Last element is:"); System.out.println(al.get(al.size()-1)); } } }
🌐
Java Guides
javaguides.net › 2024 › 05 › java-get-last-element-of-list.html
Java: Get Last Element of List
May 29, 2024 - Getting the last element of a list in Java can be accomplished using various methods, including the size method and ListIterator.
Top answer
1 of 7
134

Do a reduction that simply returns the current value:

Stream<T> stream;
T last = stream.reduce((a, b) -> b).orElse(null);
2 of 7
39

This heavily depends on the nature of the Stream. Keep in mind that “simple” doesn’t necessarily mean “efficient”. If you suspect the stream to be very large, carrying heavy operations or having a source which knows the size in advance, the following might be substantially more efficient than the simple solution:

static <T> T getLast(Stream<T> stream) {
    Spliterator<T> sp=stream.spliterator();
    if(sp.hasCharacteristics(Spliterator.SIZED|Spliterator.SUBSIZED)) {
        for(;;) {
            Spliterator<T> part=sp.trySplit();
            if(part==null) break;
            if(sp.getExactSizeIfKnown()==0) {
                sp=part;
                break;
            }
        }
    }
    T value=null;
    for(Iterator<T> it=recursive(sp); it.hasNext(); )
        value=it.next();
    return value;
}

private static <T> Iterator<T> recursive(Spliterator<T> sp) {
    Spliterator<T> prev=sp.trySplit();
    if(prev==null) return Spliterators.iterator(sp);
    Iterator<T> it=recursive(sp);
    if(it!=null && it.hasNext()) return it;
    return recursive(prev);
}

You may illustrate the difference with the following example:

String s=getLast(
    IntStream.range(0, 10_000_000).mapToObj(i-> {
        System.out.println("potential heavy operation on "+i);
        return String.valueOf(i);
    }).parallel()
);
System.out.println(s);

It will print:

potential heavy operation on 9999999
9999999

In other words, it did not perform the operation on the first 9999999 elements but only on the last one.

🌐
GeeksforGeeks
geeksforgeeks.org › java › get-first-and-last-elements-from-arraylist-in-java
Get first and last elements from ArrayList in Java - GeeksforGeeks
July 11, 2025 - Use get(0) to access the first element of an ArrayList. Use get(size() - 1) to access the last element. Always check whether the list is null or empty before accessing its elements.