Given a stream containing some elements, the task is to get the first element of the Stream in Java.
Example:
Input: Stream = {“Geek_First”, “Geek_2”, “Geek_3”, “Geek_4”, “Geek_Last”}
Output: Geek_First
Input: Stream = {1, 2, 3, 4, 5, 6, 7}
Output: 1
There are many methods to the find first 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 first 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
firstElementInStream(Stream<T> stream)
{
T first_element
= stream
.reduce((first, second) -> first)
.orElse( null );
return first_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(
"First Element: "
+ firstElementInStream(stream));
}
}
|
Output:
First Element: Geek_First
- Using Stream findFirst() Method: The findFirst() method will returns the first element of the stream or an empty if the stream is empty.
Approach:
- Get the stream of elements in which the first element is to be returned.
- To get the first element, you can directly use the findFirst() method.
Stream.findFirst()
- This will return the first element of the stream.
Below is the implementation of the above approach:
Example:
import java.util.*;
import java.util.stream.*;
public class GFG {
public static <T> T
firstElementInStream(Stream<T> stream)
{
T first_element
= stream
.findFirst()
.orElse( null );
return first_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(
"First Element: "
+ firstElementInStream(stream));
}
}
|
Output:
First Element: Geek_First