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();
Answer from nosid on Stack Overflow
Top answer
1 of 10
284

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.

🌐
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 - Learn to find the last element of a stream in Java 8 or later. We will use stream reduction technique as well as guava's Streams.findLast() method.
🌐
GeeksforGeeks
geeksforgeeks.org › java › find-the-last-element-of-a-stream-in-java
Find the last element of a Stream in Java - GeeksforGeeks
July 12, 2025 - To get the last element, you can use the reduce() method to ignore the first element, repeatedly, till there is no first element. ... This reduces the set of elements in a Stream to a single element, which is last.
🌐
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 - package com.mkyong; import java.util.Arrays; import java.util.List; public class Java8Example1 { public static void main(String[] args) { List<String> list = Arrays.asList("node", "java", "c++", "react", "javascript"); String result = list.stream().reduce((first, second) -> second).orElse("no last element"); System.out.println(result); } } ... package com.mkyong; import java.util.Arrays; import java.util.List; public class Java8Example2 { public static void main(String[] args) { List<String> list = Arrays.asList("node", "java", "c++", "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 = list.stream().skip(list.size() - 1).findFirst().orElse("no last element"); System.out.println(result2); } }
🌐
TutorialsPoint
tutorialspoint.com › find-the-last-element-of-a-stream-in-java
Find the Last Element of a Stream in Java
July 31, 2023 - To work with streams in Java, the syntax includes making a stream from a data source, applying intermediate operations to convert the stream, and ending with a terminal operation. The common sentence structure for finding the final component of a stream is as takes after ? Optional<T> lastElement = stream.reduce((first, second) -> second);
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.

Find elsewhere
🌐
YouTube
youtube.com › interview dot
JAVA 8 STREAM FIND LAST ELEMENT FROM LIST USING SKIP | JAVA EXAMPLE CODE DEMO | InterviewDOT - YouTube
#JAVACODING #JAVA8STREAM #JAVAEXAMPLECODE #JAVASKIPClick here - https://www.youtube.com/channel/UCd0U_xlQxdZynq09knDszXA?sub_confirmation=1 to get notificati...
Published   May 26, 2021
Views   836
🌐
Java Tips
javatips.net › blog › find-last-element-of-a-stream
Find Last Element Of A Stream - Javatips.net
September 10, 2019 - Note: we are using stream.reduce function for finding the last element of a stream in java. Stream.reduce method always returns Optional value, so you have to decide what to do when empty element is returned. The best way to get the last element of a stream is you can use stream().reduce method ...
🌐
Level Up Lunch
leveluplunch.com › java › examples › find-last-element-java8-stream
Find last element of java 8 stream | Level Up Lunch
August 11, 2015 - This native java way is not as eloquent as getting the last segment in a list in groovy or finding the last value in an list. @Test public void last_element_stream() { Optional<String> optionalJava = Stream.of("a", "b", "c").reduce( (a, b) -> b); assertEquals("c", optionalJava.get()); String lastValue = Stream.of("a", "b", "c").reduce((a, b) -> b) .orElse("false"); assertEquals("c", lastValue); }
🌐
Java Guides
javaguides.net › 2024 › 09 › java-8-how-to-get-last-element-of-stream.html
Java 8 – How to Get the Last Element of a Stream
September 9, 2024 - Convert to List and Access Last Element: Convert the stream to a list and get the last element. Use Reduce Operation: Use the reduce() method to keep track of the last processed element. import java.util.Arrays; import java.util.List; public ...
🌐
Blogger
java8example.blogspot.com › 2019 › 09 › java-stream-last-element.html
Java 8: How to Get the Last Element of a Stream in Java? Java8Example
September 11, 2019 - package com.java.w3schools.blog.java8.stream; import java.util.ArrayList; import java.util.List; import java.util.Optional; public class StreamLastElement { public static void main(String[] args) { List · values = new ArrayList<>(); values.add("First"); values.add("Second"); values.add("Third"); values.add("Fourth"); values.add("Last"); Optional · lastOptional = values.stream().reduce((str1, str2) -> str2); String lastValue = lastOptional.get(); System.out.println("last value using reduce api: " + lastValue); } } reduce() method takes BiFunction functional interface as an argument.
🌐
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 - package in.bench.resources.find.list; import java.util.ArrayList; import java.util.List; public class FindFirstAndLastElementInArrayList { public static void main(String[] args) { // local variables String first = null; String last = null; // create List object List<String> names = new ArrayList<>(); // add names to newly created ArrayList names.add("Deepinder Goyal"); names.add("Vinay Sanghi"); names.add("Bipin Preet Singh"); names.add("Vijay Shekhar Sharma"); names.add("Falguni Nayar"); // find First and Last element of ArrayList if(!names.isEmpty()) { first = names.get(0); last = names.get(names.size() - 1); } // print to console System.out.println("First name in the List is = " + first); System.out.println("Last name in the List is = " + last); } } ... https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#reduce-java.util.function.BinaryOperator-
🌐
@ankurm
ankurm.com › home › java stream api: how to get the last element
Java Stream API: How to Get the Last Element
November 15, 2025 - The reduce() operation processes each element while retaining only the last one seen. This approach works beautifully for both sequential and parallel streams. import java.util.Optional; import java.util.stream.Stream; public class LastElementWithReduce { public static void main(String[] args) { Stream fruitStream = Stream.of("apple", "banana", "cherry", "date"); Optional lastElement = fruitStream.reduce((first, second) -> second); lastElement.ifPresent(element -> System.out.println("Last fruit: " + element) ); } }
🌐
Coderanch
coderanch.com › t › 777931 › java › Reduce-Stream-Element
Reduce Stream to Contain Last Element Only (Features new in Java 8 forum at Coderanch)
November 30, 2023 - Note that it only evaluates the last element. For some streams, it might end up having to evaluate more, in cases where it's hard for the Spliterator to estimate size correctly and some splits might not contain any actual elements. ... This has been enlightening. Here's both together with some timing. ... JavaRanch-FAQ HowToAskQuestionsOnJavaRanch UseCodeTags DontWriteLongLines ItDoesntWorkIsUseLess FormatCode JavaIndenter SSCCE API-17 JLS JavaLanguageSpecification MainIsAPain KeyboardUtility
🌐
CodeVsColor
codevscolor.com › how to get the last element of a stream in java - codevscolor
How to get the last element of a stream in Java - CodeVsColor
January 26, 2021 - reduce is used to get one value from a stream. We can use reduce to return the last element of a stream. ... import java.util.*; class Main { public static void main(String[] args) { List<Integer> integerList = new ArrayList<>(Arrays.asList(1, ...
🌐
GitHub
github.com › amaembo › streamex › issues › 103
last() on stream · Issue #103 · amaembo/streamex
August 16, 2016 - Hi Tagir, awesome library! Anyway, I always missed a simple last() method to retrieve the last element of a stream Actually I am doing .reduce((a, b) -> b).orElse(null) Would it be possible?
Author   elect86
🌐
CodeSpeedy
codespeedy.com › home › java : how to get the last element of a stream?
Java : How to get the last element of a stream? - CodeSpeedy
June 5, 2020 - Apparently, Stream.skip returns the value by skipping all the elements before the last element in a set of elements. Here, I have presented the sample code of it. import java.util.*; public class useOfStreamSkip { public static void main(String[] args) { List<String> mylist = Arrays.asList("A", "T", "C", "G"); // Here we get the last element from a stream, via skip String lastItem = mylist.stream().skip(mylist.size() -1).findFirst().orElse("The last element does not exists"); System.out.println(lastItem); } }
🌐
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 - 2. A list named strings is created and initialized with an array of string values. 3. To find the last element, the program converts the list into a stream using the stream() method.