Java : How to get the last element of a stream?

In this, we are going to understand how we can get the last element of a stream in Java. This can be done via reduce or skip methods in Java.

1. Using Stream.reduce() :

Stream.reduce is required to deliver results by reducing to a single element from a set of given elements.

Here, I have presented the sample code of it.

Code:

Below I have shown a program that will help to get the last element of a stream using the Stream.reduce() method.

import java.util.*; 
public class useOfStreamReduce { 
public static void main(String[] args) { 
List<String> mylist = Arrays.asList("A", "T", "C", "G"); 
// Here we get the last element from a stream, via reduce
String lastItem = mylist.stream().reduce((first, second) -> second).orElse("The last element does not exists");
System.out.println(lastItem); 
} 
}

Output:

Below is the output of the above code.

G

2. Using Stream.skip() :

Below I have shown a Java code that will help to get the last element of a stream using Stream.skip().

Apparently, Stream.skip returns the value by skipping all the elements before the last element in a set of elements.

Here, I have presented the sample code of it.

Code:

import java.util.*; 
public class useOfStreamSkip { 
public static void main(String[] args) { 
List<String> mylist = Arrays.asList("A", "T", "C", "G"); 
// Here we get the last element from a stream, via skip
String lastItem = mylist.stream().skip(mylist.size() -1).findFirst().orElse("The last element does not exists"); System.out.println(lastItem); 
} 
}

Output:

Below is the output of the above code.

G

You can learn more by clicking here:   Check this also! Learn!

Leave a Reply