Iterable is a core interface in Java that represents a collection of elements that can be traversed one by one. Although it supports iteration through an Iterator, it does not provide a direct stream() method, so it must be converted into a Stream to leverage the Java 8 Stream API.
- Bridges traditional iteration with the functional programming features introduced in Java 8.
- Allows stream pipelines to perform operations such as filtering, mapping, sorting, and collecting.
Convert an Iterable to a Stream Using StreamSupport.stream()
The StreamSupport.stream() method is the standard way to convert an Iterable into a sequential stream. It internally uses the Spliterator of the Iterable to create the stream.
Syntax:
StreamSupport.stream(
iterable.spliterator(), false
);
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'}
To convert an Iterable into a Stream, follow these steps:
- Obtain the Iterable containing the elements.
- Retrieve its Spliterator using the spliterator() method.
- Pass the Spliterator to StreamSupport.stream() and specify false to create a sequential stream.
- Use the returned Stream to perform Stream API operations such as filter(), map(), collect(), or forEach().
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));
}
}
Output
1 2 3 4 5
Benefits After Conversion
Converting an Iterable to a Stream allows developers to use the powerful operations provided by the Stream API. Instead of manually iterating through elements using an Iterator or enhanced for loop, streams enable processing through a sequence of chained operations.
- Reduces boilerplate code by eliminating explicit iteration.
- Supports sequential and parallel stream processing.
- Improves code readability and maintainability.