Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Convert an Iterable to Stream in Java
What is an Iterable?
Iterable is an Interface that is used for iterating over a Collection of objects. It is part of the Java Collections Framework. The Iterable interface is implemented by all the collection classes in Java.
For example, ArrayList, HashSet, etc. The Iterable interface has a method named iterator() which returns an Iterator object.
What is a Stream?
Stream is an Interface that is used for processing sequences of elements. It is part of the Java Collections Framework. The Stream interface is a newly added abstraction in Java 8.
It is mainly used for sequential operations on collections, for example, filtering, mapping, and reducing. Sometimes we need to convert an Iterable to a Stream. In this article, we will learn how to convert an Iterable to a Stream in Java using the StreamSupport class.
Converting Iterable to a Stream using StreamSupport
In this method, we will use the StreamSupport class to convert an Iterable to a Stream. The StreamSupport class is a utility class that provides static methods for creating streams.
We will use the StreamSupport.stream() method to convert an Iterable to a Stream. The syntax of the StreamSupport.stream() method is as follows -
stream(Iterable<T> iterable, boolean parallel)
Example
Following is the code to convert an Iterable to a Stream using the StreamSupport class -
import java.util.*;
import java.io.*;
import java.util.stream.*;
public class IterableToStream {
public static void main(String[] args) {
// Create an Iterable object
Iterable<String> iterable = Arrays.asList("A", "B", "C", "D", "E");
// Convert the Iterable to a Stream using StreamSupport
Stream<String> stream = StreamSupport.stream(iterable.spliterator(), false);
// Print the Stream
stream.forEach(System.out::println);
}
}
Output
The output of the above code will be:
A B C D E
