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:
Approach:
Stream.reduce((first, second) -> first)
Below is the implementation of the above approach:
Example:
// 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 firstElementInStream(Stream 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 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
2. Using Stream findFirst() Method:
Approach:
Stream.findFirst()
Below is the implementation of the above approach:
Example:
// 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 firstElementInStream(Stream 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 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