Java 8 – How to Get the Last Element of a Stream

Introduction

Streams in Java 8 are designed for processing collections in a functional way, but they do not directly provide a method to retrieve the last element. This is because streams are processed in a forward-only manner. However, we can still find the last element of a stream using a few different approaches, depending on whether the stream is ordered or unordered.

In this guide, we will explore two methods to get the last element of a stream: one for finite, ordered streams and another using a reduction operation.

Solution Steps

  1. Convert to List and Access Last Element: Convert the stream to a list and get the last element.
  2. Use Reduce Operation: Use the reduce() method to keep track of the last processed element.

Java Program

Method 1: Convert Stream to List

import java.util.Arrays;
import java.util.List;

public class LastElementOfStream {
    public static void main(String[] args) {
        // Step 1: Define a list and create a Stream
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7);

        // Step 2: Convert the Stream to a List and get the last element
        Integer lastElement = numbers.stream()
                                     .reduce((first, second) -> second)  // Reduce to get last element
                                     .orElse(null);  // Handle case where stream is empty

        // Step 3: Display the last element
        System.out.println("Last element: " + lastElement);
    }
}

Output

Last element: 7

Explanation

  • Step 1: We define a list of integers, which serves as the source for the stream.
  • Step 2: The reduce() method is used to iterate over the stream. The lambda expression (first, second) -> second keeps updating the value with the current element until the last element is reached.
    • If the stream is empty, orElse(null) will return null as a fallback.
  • Step 3: The last element is printed to the console.

Method 2: Convert Stream to List and Get Last Element

Another approach is to convert the stream into a List and then access the last element directly.

Example

import java.util.Arrays;
import java.util.List;

public class LastElementOfStreamUsingList {
    public static void main(String[] args) {
        // Step 1: Define a list and create a Stream
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7);

        // Step 2: Convert the Stream to a List
        List<Integer> numberList = numbers.stream().toList();

        // Step 3: Get the last element from the list
        Integer lastElement = numberList.isEmpty() ? null : numberList.get(numberList.size() - 1);

        // Step 4: Display the last element
        System.out.println("Last element: " + lastElement);
    }
}

Output

Last element: 7

Explanation

  • Step 1: We start by defining the list, which will be converted to a stream.
  • Step 2: The stream().toList() method converts the stream back into a list.
  • Step 3: We access the last element of the list using numberList.get(numberList.size() - 1) and check if the list is empty.
  • Step 4: The last element is printed.

Conclusion

In Java 8, although there is no direct method to retrieve the last element of a stream, we can achieve this using either the reduce() method or by converting the stream into a list and accessing the last element. Both approaches are efficient for different scenarios, depending on the size of the stream and the nature of the data.

Comments