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.

🌐
Baeldung
baeldung.com › home › java › java streams › how to get the last element of a stream in java?
How to Get the Last Element of a Stream in Java? | Baeldung
January 8, 2024 - Get started with the Reactor project basics and reactive programming in Spring Boot: ... Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.
🌐
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.
🌐
TutorialsPoint
tutorialspoint.com › find-the-last-element-of-a-stream-in-java
Find the Last Element of a Stream in Java
July 31, 2023 - Check if the stream was not empty and get the last element if present. import java.util.Optional; import java.util.stream.Stream; public class LastElementFinder { public static <T> Optional<T> findLastElement(Stream<T> stream) { return stream.reduce((first, second) -> second); } public static void main(String[] args) { Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5); Optional<Integer> lastElement = findLastElement(stream); lastElement.ifPresent(System.out::println); } }
🌐
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); } }
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.

🌐
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
Find elsewhere
🌐
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); }
🌐
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.blo... String lastValue = lastOptional.get(); System.out.println("last value using reduce api: " + lastValue); } } reduce() method takes BiFunction functional interface as an argument....
🌐
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, ...
🌐
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 ...
🌐
YouTube
youtube.com › interview dot
Find The Last Element From A List Using Java 8 Stream Reduce() | Skip() | InterviewDOT - YouTube
Click here - https://www.youtube.com/channel/UCd0U_xlQxdZynq09knDszXA?sub_confirmation=1 to get notifications.Find The Last Element From A List Using Java 8 ...
Published   June 6, 2020
Views   452
🌐
@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) ); } }
Top answer
1 of 4
7

You could use skip:

elements.stream().skip(elements.size() - 2)

From the API:

Returns a stream consisting of the remaining elements of this stream after discarding the first n elements of the stream. If this stream contains fewer than n elements then an empty stream will be returned.

Probably useless example:

// a list made of a, b, c and d
List<String> l = Arrays.asList("a", "b", "c", "d");

// prints c and d
l.stream().skip(l.size() - 2).forEach(System.out::println);

Probably useless note:

As mentioned by a few, this only works if you have a size to work with, i.e. if you're streaming from a collection.

Quoting Nicolas, a stream doesn't have a size.

2 of 4
2

You could do a bit of inlining of your original approach, which I think shortens it up nicely, and you don't even have to use a stream:

    String[] a = fullDomain.split("\\.");
    return String.join(".", Arrays.asList(a)
                                  .subList(Math.max(0, a.length-2), a.length));

If you really want to use a stream, you can use the array-subrange stream source:

    String[] a = fullDomain.split("\\.");
    return Arrays.stream(a, Math.max(0, a.length-2), a.length)
                 .collect(Collectors.joining("."));

If all you have is a stream, whose size you don't have in advance, I'd just dump the elements into an ArrayDeque:

    final int N = 2;
    Stream<String> str = ... ;

    Deque<String> deque = new ArrayDeque<>(N);
    str.forEachOrdered(s -> {
        if (deque.size() == N) deque.removeFirst();
        deque.addLast(s);
    });
    return String.join(".", deque);

Of course, this isn't as general as writing a collector, but for simple cases it's probably just fine.

🌐
GitHub
github.com › amaembo › streamex › issues › 103
last() on stream · Issue #103 · amaembo/streamex
August 16, 2016 - last() on stream#103 · Copy link · elect86 · opened · on Aug 16, 2016 · Issue body actions · Hi Tagir, awesome library! Anyway, I always missed a simple last() method to retrieve the last element of a stream · Actually I am doing · ...
Author   elect86
🌐
Lambdafaq
lambdafaq.org › how-can-i-get-the-last-element-of-a-stream
How can I get the last element of a stream? | Maurice Naftalin's Lambda FAQ
February 7, 2015 - Your questions answered: all about Lambdas and friends · The simplest way is something like the following: