- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Convert an Iterable to Stream in Java
Let’s say the following is our Iterable −
Iterable<String> i = Arrays.asList("K", "L", "M", "N", "O", "P");
Now, create a Collection −
Stream<String> s = convertIterable(i);
Above, we have a custom method convertIterable() for conversion. Following is the method −
public static <T> Stream<T> convertIterable(Iterable<T> iterable) { return StreamSupport.stream(iterable.spliterator(), false); }
Example
Following is the program to convert an Iterable to Stream in Java −
import java.util.*; import java.util.stream.*; public class Demo { public static <T> Stream<T> convertIterable(Iterable<T> iterable) { return StreamSupport.stream(iterable.spliterator(), false); } public static void main(String[] args) { Iterable<String> i = Arrays.asList("K", "L", "M", "N", "O", "P"); Stream<String> s = convertIterable(i); System.out.println("Iterable to Stream: "+s.collect(Collectors.toList())); } }
Output
Iterable to Stream: [K, L, M, N, O, P]
Advertisements