A java stream is a sequence of elements and at some time you might be required to know the last stream element.
There are three methods of getting the last element of a stream.

Method 1: Using reduce method
reduce method of a stream takes a parameter of type java.util.function.BinaryOperator which is a functional interface having a single method apply.
This method accepts two arguments and returns a result.

Thus, we can supply a Lambda expression to reduce matching the signature of apply .
This lamdba expression takes two elements and just returns the second element, then at the end of stream we will be getting the last element.
Example,

List<Integer> list = Arrays.asList(new Integer[] {1,2,3,55,67,34,20});
Integer lastElement = list.stream().
                           reduce((first, second) -> second).
                           orElse(null);

This method will return null if the stream is empty.
Method 2: Using skip
skip method of java.util.stream.Stream accepts a numeric value and skip the number of stream elements equal to this value.
It returns a stream with remaining elements after skipping those elements.

Thus, if skip is supplied a number which is one less than the total number of elements in the stream, then the resulting stream will have the last element. Example,

List<Integer> list = Arrays.asList(new Integer[] {1,2,3,55,67,34,20});
// total number of stream elements
long count = list.stream().count();
// element at count -1 position
Integer last = list.stream().
                    skip(count - 1).
                    findFirst().
                    get();

For getting the total number of stream elements, count() method is used.
Also, skip() returns a stream, use its findFirst() method to get the first stream element.
findFirst() returns an Optional object, use its get() method to get the value of element.

Method 3: Using guava library
Guava library has a class com.google.common.collect.Streams which has a findLast() method.
This method takes a stream as argument and returns its last element. Example,

List<Integer> list = Arrays.asList(new Integer[] {1,2,3,55,67,34,20});
Optional<Integer> lastElement = com.google.common.collect.Streams.findLast(list.stream());
Integer last = lastElement.get();

findLast() method returns an Optional object, hence you need to call its get() method to get the value of last element.
These are the three ways in which last element of stream can be retrieved. Hit the clap if the article was useful

1

Share your thoughts !!

Close Menu

Never Miss an article !

Get the new post delivered straight into your inbox, enter your email and hit the button

You have successfully subscribed to the newsletter

There was an error while trying to send your request. Please try again.

codippa will use the information you provide on this form to be in touch with you and to provide updates and marketing.