Last Updated : 11 Dec, 2018
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:
Below is the implementation of the above approach:
Java
// 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));
}
}
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