Given an Iterable, the task is to convert it into Stream in Java.
Examples:
Input: Iterable = [1, 2, 3, 4, 5]
Output: {1, 2, 3, 4, 5}
Input: Iterable = ['G', 'e', 'e', 'k', 's']
Output: {'G', 'e', 'e', 'k', 's'}
Approach:
- Get the Iterable.
- Convert the Iterable to Spliterator using Iterable.spliterator() method.
- Convert the formed Spliterator into Sequential Stream using StreamSupport.stream() method.
- Return the stream.
Below is the implementation of the above approach:
// Java program to get a Stream // from a given Iterable import java.util.*; import java.util.stream.*; class GFG { // Function to get the Stream public static <T> Stream<T> getStreamFromIterable(Iterable<T> iterable) { // Convert the Iterable to Spliterator Spliterator<T> spliterator = iterable.spliterator(); // Get a Sequential Stream from spliterator return StreamSupport.stream(spliterator, false); } // Driver code public static void main(String[] args) { // Get the Iterator Iterable<Integer> iterable = Arrays.asList(1, 2, 3, 4, 5); // Get the Stream from the Iterable Stream<Integer> stream = getStreamFromIterable(iterable); // Print the elements of stream stream.forEach(s -> System.out.println(s)); } } |
chevron_right
filter_none
Output:
1 2 3 4 5
Attention reader! Don’t stop learning now. Get hold of all the important Java and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.
Recommended Posts:
- Convert an Iterable to Collection in Java
- Convert Iterator to Iterable in Java
- Java | Implementing Iterator and Iterable Interface
- Iterable forEach() method in Java with Examples
- Character Stream Vs Byte Stream in Java
- Difference between Stream.of() and Arrays.stream() method in Java
- foreach() loop vs Stream foreach() vs Parallel Stream foreach()
- Convert Stream to Set in Java
- Convert a Set to Stream in Java
- Program to convert a Set to Stream in Java using Generics
- Program to Convert List to Stream in Java
- Program to Convert Stream to an Array in Java
- Program to convert Boxed Array to Stream in Java
- Program to convert Primitive Array to Stream in Java
- Program to convert a Map to a Stream in Java
- Convert an Iterator to Stream in Java
- How to convert a Stream into a Map in Java
- Java Stream | Collectors toCollection() in Java
- Stream In Java
- java.util.stream.IntStream/LongStream | Search an element
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

