Java 8 – Get the Last Element from a List

Introduction

Retrieving the last element from a list is a common task in programming, especially when dealing with collections where the order of elements matters. While accessing the last element of a list might seem straightforward, Java 8 Streams provide a functional approach to perform this operation. In this guide, we’ll explore how to get the last element from a list using Java 8 Streams, covering both primitive types and custom objects.

Table of Contents

  • Problem Statement
  • Solution Steps
  • Java Program
    • Getting the Last Element from a List of Integers
    • Getting the Last Element from a List of Strings
    • Getting the Last Element from a List of Custom Objects
  • Advanced Considerations
  • Conclusion

Problem Statement

The task is to create a Java program that:

  • Accepts a list of elements.
  • Retrieves the last element in the list.
  • Outputs the last element.

Example 1:

  • Input: List of integers [1, 3, 7, 0, 5]
  • Output: 5

Example 2:

  • Input: List of custom Student objects, retrieve the last Student in the list.
  • Output: The last Student object.

Solution Steps

  1. Input List: Start with a list of elements that can either be hardcoded or provided by the user.
  2. Get the Last Element Using Streams: Use reduce() or list indexing to retrieve the last element in the list.
  3. Display the Result: Print the last element.

Java Program

Getting the Last Element from a List of Integers

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

/**
 * Java 8 - Get the Last Element from a List of Integers Using Streams
 * Author: https://www.rameshfadatare.com/
 */
public class GetLastElementInList {

    public static void main(String[] args) {
        // Step 1: Take input list
        List<Integer> numbers = Arrays.asList(1, 3, 7, 0, 5);

        // Step 2: Get the last element in the list using reduce
        Optional<Integer> lastNumber = numbers.stream()
                                              .reduce((first, second) -> second);

        // Step 3: Display the result
        lastNumber.ifPresent(num -> System.out.println("Last element: " + num));
    }
}

Output

Last element: 5

Explanation

  • The stream() method is used to create a stream from the list of integers.
  • The reduce() method is applied to the stream, where the accumulator keeps only the last element encountered.
  • The result is an Optional<Integer>, which is used to safely print the last element.
  • The output shows that the last element in the list is 5.

Getting the Last Element from a List of Strings

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

/**
 * Java 8 - Get the Last Element from a List of Strings Using Streams
 * Author: https://www.rameshfadatare.com/
 */
public class GetLastStringInList {

    public static void main(String[] args) {
        // Step 1: Take input list
        List<String> fruits = Arrays.asList("apple", "banana", "orange");

        // Step 2: Get the last element in the list using reduce
        Optional<String> lastFruit = fruits.stream()
                                           .reduce((first, second) -> second);

        // Step 3: Display the result
        lastFruit.ifPresent(fruit -> System.out.println("Last fruit: " + fruit));
    }
}

Output

Last fruit: orange

Explanation

  • The stream() method is used to create a stream from the list of strings.
  • The reduce() method is applied, where the accumulator retains only the last element encountered.
  • The result is an Optional<String>, which is used to safely print the last element.
  • The output shows that the last element in the list is "orange".

Getting the Last Element from a List of Custom Objects

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

/**
 * Java 8 - Get the Last Element from a List of Custom Objects Using Streams
 * Author: https://www.rameshfadatare.com/
 */
public class GetLastCustomObjectInList {

    public static void main(String[] args) {
        // Step 1: Take input list of custom objects
        List<Student> students = Arrays.asList(
                new Student("Raj", 25),
                new Student("Anita", 30),
                new Student("Vikram", 22)
        );

        // Step 2: Get the last element in the list using reduce
        Optional<Student> lastStudent = students.stream()
                                                .reduce((first, second) -> second);

        // Step 3: Display the result
        lastStudent.ifPresent(student -> 
            System.out.println("Last student: " + student.getName() + ", Age: " + student.getAge())
        );
    }
}

// Custom class Student
class Student {
    private String name;
    private int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}

Output

Last student: Vikram, Age: 22

Explanation

  • The list of Student objects is processed to retrieve the last element.
  • The reduce() method is used to get the last Student in the stream.
  • The result is an Optional<Student>, which is used to safely print the details of the last Student.
  • The output shows that the last Student in the list is "Vikram," who is 22 years old.

Advanced Considerations

  • Handling Empty Lists: The reduce() method returns an Optional, which is a safe way to handle cases where the list might be empty. If the list is empty, the Optional will be empty, and you can handle this case appropriately.

  • Performance Considerations: Using reduce() on a stream to find the last element is efficient for most use cases. However, for very large lists, consider using traditional list indexing (list.get(list.size() - 1)) if the performance is a concern.

  • Parallel Streams: When using parallel streams, reduce() might not guarantee the last element in encounter order. For parallel processing, it’s better to use a custom collector if you need to ensure correct ordering.

Conclusion

This guide provides methods for retrieving the last element from a list using Java 8 Streams, covering both simple lists like integers and strings, as well as more complex lists like custom objects. Java 8 Streams offer a powerful and concise way to perform this operation, making your code more readable and maintainable. Depending on your specific use case, you can easily apply the techniques demonstrated in this guide to get the last element from a list.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top