How to get the last element of a stream in Java

How to get the last element of a stream in Java:

In this post, we will learn how to get the last element of a Java Stream. We can use reduce or skip methods to get the last element of a stream.

Using reduce:

reduce is used to get one value from a stream. We can use reduce to return the last element of a stream.

Let’s try reduce with a list of integers:

import java.util.*;

class Main {
    public static void main(String[] args) {
        List<Integer> integerList = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9));

        Optional<Integer> lastElement = integerList.stream().reduce((first, second) -> second);

        System.out.println(lastElement.get());
    }
}

This program will print 9.

Using skip:

Another way to solve this problem is by using skip function. Using it, we can skip to the last element of the stream. We can get the stream count by using count() function and skip to the end.

Let me change the above program to use skip:

import java.util.*;

class Main {
    public static void main(String[] args) {
        List<Integer> integerList = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9));

        long count = integerList.stream().count();
        Integer lastValue = integerList.stream().skip(count - 1).findFirst().get();
        System.out.println(lastValue);
    }
}

It will also print 9.

You might also like: