Close

How to find first and last element of Java 8 stream?

[Last Updated: Apr 22, 2020]

Java 8 Streams Java 

Following example shows how to find first and last element of a Java 8 stream:

package com.logicbig.example;

import java.util.Arrays;
import java.util.Collection;

public class FirstLastElement {
    public static void main(String[] args) {
        Collection<String> fruits = Arrays.asList("apple", "banana", "pie", "pineapple", "apricots");

        String firstElement = fruits.stream()
                                    .findFirst()
                                    .orElse(null);

        String lastElement = fruits.stream().skip(fruits.size() - 1)
                                   .reduce((first, second) -> second)
                                   .orElse(null);

        System.out.println("First: " + firstElement);
        System.out.println("Last: " + lastElement);
    }
}
First: apple
Last: apricots

See Also