Find the last element of a Stream in Java
Last Updated :
04 Apr, 2020
Given a stream containing some elements, the task is to get the last element of the Stream in Java.
Example:
Input: Stream={“Geek_First”, “Geek_2”, “Geek_3”, “Geek_4”, “Geek_Last”}
Output: Geek_Last
Input: Stream={1, 2, 3, 4, 5, 6, 7}
Output: 7
There are many methods to find last elements in a Stream:
- Using Stream.reduce() Method: The reduce method works on two elements in the stream and returns the element as per the required condition. Therefore this method can be used to reduce the stream so that it contains only the last element.
Approach:
Below is the implementation of the above approach:
Example:
import java.util.*;
import java.util.stream.*;
public class GFG {
public static <T> T
lastElementInStream(Stream<T> stream)
{
T last_element
= stream
.reduce((first, second) -> second)
.orElse( null );
return last_element;
}
public static void main(String[] args)
{
Stream<String> stream
= Stream.of( "Geek_First" , "Geek_2" ,
"Geek_3" , "Geek_4" ,
"Geek_Last" );
System.out.println(
"Last Element: "
+ lastElementInStream(stream));
}
}
|
Output:
Last Element: Geek_Last
- Using Stream skip() Method: The skip() method returns a stream after removing first N elements. Therefore this method can be used to skip the elements except the last one.
Approach:
Below is the implementation of the above approach:
Example:
import java.util.*;
import java.util.stream.*;
public class GFG {
public static <T> T
lastElementInStream(Stream<T> stream, int N)
{
T last_element
= stream
.skip(N - 1 )
.findFirst()
.orElse( null );
return last_element;
}
public static void main(String[] args)
{
Stream<String> stream
= Stream.of( "Geek_First" , "Geek_2" ,
"Geek_3" , "Geek_4" ,
"Geek_Last" );
int N = 5 ;
System.out.println(
"Last Element: "
+ lastElementInStream(stream, N));
}
}
|
Output:
Last Element: Geek_Last
- Find the first element of the reversed stream:
Approach:
Below is the implementation of the above approach:
Example:
import java.util.*;
import java.util.stream.*;
public class GFG {
public static <T> T
lastElementInStream(Stream<T> stream)
{
T last_element
= stream
.sorted(Collections.reverseOrder())
.findFirst()
.orElse( null );
return last_element;
}
public static void main(String[] args)
{
Stream<String> stream
= Stream.of( "Geek_First" , "Geek_2" ,
"Geek_3" , "Geek_4" ,
"Geek_Last" );
System.out.println(
"Last Element: "
+ lastElementInStream(stream));
}
}
|
Output:
Last Element: Geek_Last
Share your thoughts in the comments
Please Login to comment...