Find last element of java 8 stream

In this sample we will show how to get the last element within a stream. Initializing a stream with a string values in both snippets we will call the reduce method passing in a function to return the current value. The difference between the two is the first will return a java 8 optional where we should first check if there is present value. The second uses orElse which returns the value passed if no values are present. In this case there is a possibility that the value returned could be null. This native java way is not as eloquent as getting the last segment in a list in groovy or finding the last value in an list.

Stream Reduce

@Test
public void last_element_stream() {

    Optional<String> optionalJava = Stream.of("a", "b", "c").reduce(
            (a, b) -> b);

    assertEquals("c", optionalJava.get());

    String lastValue = Stream.of("a", "b", "c").reduce((a, b) -> b)
            .orElse("false");

    assertEquals("c", lastValue);
}