Convert an Iterable to Stream in Java

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:



  1. Get the Iterable.
  2. Convert the Iterable to Spliterator using Iterable.spliterator() method.
  3. Convert the formed Spliterator into Sequential Stream using StreamSupport.stream() method.
  4. Return the stream.

Below is the implementation of the above approach:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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


Output:

1
2
3
4
5


My Personal Notes arrow_drop_up

Technical Content Engineer at GeeksForGeeks

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.