Get the Last Element of a Stream in Java

1). Using Stream.reduce() Method:

The reduce method works on two elements in the stream and returns the element as given condition. Therefore this method can be used to reduce the stream so that it contains only the last element.

Get the stream of elements in which the first element is to be returned. To get the last element, you can use the reduce() method to ignore the first element, repeatedly, till there is no first element. Stream.reduce((first, second) -> second)

Hence the only single element will be remain in the stream which is the last element.

Stream<Integer> stream = Arrays.asList(1,11,21,31,41,51,61,71,81,91) .stream(); Integer lastElement = stream.reduce((first, second) -> second) .orElse(-1); System.out.println(lastElement); // 91

2). Using Stream skip()

The skip() method returns a stream after removing first N elements. Therefore this method can be used to skip the elements except the last one.

import java.util. * ; import java.util.stream. * ; public class GetLastElementInStream { // Function to find the // last_elements in a Stream public static < T > T getLastElementInStream(Stream < T > stream, int N) { T last_element = stream.skip(N - 1).findFirst().orElse(null); return last_element; } public static void main(String[] args) { Stream < String > stream = Stream.of("Hello", "World", "Welcome", "to", "Java", "programming", "!!"); int N = 6; // Print the last element of a Stream System.out.println("Last Element: " + getLastElementInStream(stream, N)); } }

3). Using Google collection library

The Google Guava library has Streams class,which contains findLast() method used to get last element in the given stream.

Syntax:

public static OptionalInt findLast(IntStream stream)

It returns the last element of the specified stream, or OptionalInt.empty() if the stream is empty.

Equivalent to stream.reduce((a, b) -> b), but may perform significantly better. This method's runtime will be between O(log n) and O(n), performing better on efficiently splittable streams.

Stream<Integer> stream =Arrays.asList(1,11,21,31,41,51,61,71,81,91) .stream(); Integer lastElement = Streams.findLast(stream2).orElse(-1); System.out.println(lastElement); // Prints 91

In this article, we have seen How to Get the Last Element of a Stream in Java.