Java 8 Program to Retrieve Last Element of a List of Strings

1. Introduction

Retrieving the last element of a list is a common operation in software development. With the introduction of Java 8, performing such tasks has become more straightforward thanks to the Stream API. This blog post demonstrates how to retrieve the last element of a list of strings using Java 8 features, showcasing the power and simplicity of stream operations.

2. Program Steps

1. Create a list of strings.

2. Use Java 8 Streams to process the list.

3. Retrieve the last element of the list.

4. Display the last element.

3. Code Program

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

public class RetrieveLastElement {
    public static void main(String[] args) {
        // Creating a list of strings
        List<String> strings = Arrays.asList("Java", "Python", "C++", "JavaScript", "Ruby");

        // Using Java 8 Streams to retrieve the last element
        Optional<String> lastElement =
                                              .reduce((first, second) -> second);

        // Displaying the last element
        lastElement.ifPresent(element -> System.out.println("The last element is: " + element));


The last element is: Ruby


1. The program begins by importing the necessary classes. Arrays and List from the java.util package are used to create and manage the list of strings. Optional is also imported to handle the case where the list might be empty.

2. A list named strings is created and initialized with an array of string values.

3. To find the last element, the program converts the list into a stream using the stream() method. Then, the reduce() method is applied to the stream. The reduce() operation takes two elements at a time and applies the provided lambda expression, which simply returns the second element. As this operation is applied repeatedly across the stream, it effectively returns the last element.

4. The result of the reduce() operation is an Optional<String>, which could be empty if the list is empty. The ifPresent() method on Optional is used to check if there is a last element and print it.

5. This approach demonstrates the use of the reduce() method to perform aggregation operations on stream elements, which in this case, is used creatively to retrieve the last element of the list.


Post a Comment

Leave Comment