Getting the last element of a Stream.

Transcribed from the original LinkedIn image post.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/*
Getting the last element of a stream
*/
import java.util.List;
import java.util.stream.*;

public class Day02 {
    public static void main(String[] args) {
        List<String> fileTypeList = List.of("jpg", "png", "avi", "mpeg", "docx");

        // using reduce
        String lastElement = fileTypeList.stream()
            .reduce((element1, element2) -> element2)
            .get();

        System.out.println(lastElement);

        // using skip
        String lastElement1 = fileTypeList.stream()
            .skip(fileTypeList.size() - 1)
            .findFirst()
            .get();

        System.out.println(lastElement1);
    }
}

The original LinkedIn graphic is preserved below.

Day 2 LinkedIn post