September 20, 2021

Java Stream - Get Last Element

In this tutorial we’ll see what options are there to get the last element of the stream using the Java Stream API.

1. Using reduce() method

reduce method in the Java Stream API is used to perform a reduction on the elements of the stream so that the stream is reduced to a single value. Thus it can be used to reduce the stream to a last value.

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

public class StreamLastDemo {

  public static void main(String[] args) {
    List<Integer> numList = Arrays.asList(6, 10, 5, 6, 7, 8, 12);
    int lastElement = numList.stream().reduce((f, s) -> s).orElse(-1);
    System.out.println("Last element in the Stream- " + lastElement);
  }
}
Output
Last element in the Stream- 12

2. Using skip() method

You can also use skip method to skip to the last element and then return that element. This approach is not very efficient though.

public class StreamLastDemo {

  public static void main(String[] args) {
    List<Integer> numList = Arrays.asList(6, 10, 5, 6, 7, 8, 12, 22);
    // get the stream element count
    long elementCount = numList.stream().count();
    int lastElement = -1;
    // Return -1 if not able to find last element
    if(elementCount != 0) {
      lastElement = numList.stream().skip(elementCount - 1)
                        .findFirst()
                        .orElseThrow(()->new RuntimeException("Exception Occurred"));
    }
    System.out.println("Last element in the Stream: " + lastElement);
  }
}

Output
Last element in the Stream: 22

3. Using Streams.findLast() method of Guava library

In Guava library there is a Streams class with many utility methods to be used with Stream instances. There is a findLast() method to get the last element of the stream.

import java.util.Arrays;
import java.util.List;
import com.google.common.collect.Streams;

public class StreamLastDemo {

  public static void main(String[] args) {
    List numList = Arrays.asList(6, 10, 5, 6, 7, 8, 12, 22);
    int lastElement = Streams.findLast(numList.stream()).orElse(-1);
    System.out.println("Last element in the Stream: " + lastElement);
  }
}
Output
Last element in the Stream: 22

That's all for the topic Java Stream - Get Last Element. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment