Last Updated : 12 Jul, 2025
Given a
streamcontaining 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:
Stream.reduce((first, second) -> first)
// Java program to find first
// element of a Stream in Java
import java.util.*;
import java.util.stream.*;
public class GFG {
// Function to find the
// first_elements in a Stream
public static <T> T
firstElementInStream(Stream<T> stream)
{
T first_element
= stream
// reduce() method reduces the Stream
// to a single element, which is first.
.reduce((first, second) -> first)
// if stream is empty
// null is returned
.orElse(null);
return first_element;
}
// Driver code
public static void main(String[] args)
{
Stream<String> stream
= Stream.of("Geek_First", "Geek_2",
"Geek_3", "Geek_4",
"Geek_Last");
// Print the first element of a Stream
System.out.println(
"First Element: "
+ firstElementInStream(stream));
}
}
Output:
First Element: Geek_First
Stream.findFirst()
// Java program to find first
// element of a Stream in Java
import java.util.*;
import java.util.stream.*;
public class GFG {
// Function to find the
// first_elements in a Stream
public static <T> T
firstElementInStream(Stream<T> stream)
{
T first_element
= stream
// findFirst() method returns
// the first element of stream
.findFirst()
// if stream is empty
// null is returned
.orElse(null);
return first_element;
}
// Driver code
public static void main(String[] args)
{
Stream<String> stream
= Stream.of("Geek_First", "Geek_2",
"Geek_3", "Geek_4",
"Geek_Last");
// Print the first element of a Stream
System.out.println(
"First Element: "
+ firstElementInStream(stream));
}
}
Output:
First Element: Geek_First
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4