Java 8 – Get the last element of a Stream?

In Java 8, we can use reduce or skip to get the last element of a Stream.

1. Stream.reduce

Java8Example1.java

package com.mkyong;

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

public class Java8Example1 {

    public static void main(String[] args) {

        List<String> list = Arrays.asList("node", "java", "c++", "react", "javascript");

        String result = list.stream().reduce((first, second) -> second).orElse("no last element");

        System.out.println(result);

    }

}

Output


javascript

Further Reading: Java 8 Stream.reduce() examples

2. Stream.skip

Java8Example2.java

package com.mkyong;

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

public class Java8Example2 {

    public static void main(String[] args) {

        List<String> list = Arrays.asList("node", "java", "c++", "react", "javascript");

        // get last element from a list
        String result = list.get(list.size() - 1);

        System.out.println(result);

        // get last element from a stream, via skip
        String result2 = list.stream().skip(list.size() - 1).findFirst().orElse("no last element");

        System.out.println(result2);
    }

}

Output


javascript
javascript

References

author image

mkyong

Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities. Read all published posts by

Comments

avatar