- 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 Iterator to Stream in Java
At first, set an Interator −
Iterator<Integer>iterator = Arrays.asList(50, 100, 200, 400, 500, 1000).iterator();
Now, we have used stream −
Stream<Integer>stream = convertIterator(iterator);
Above, the method convertIterator() is used for conversion. Following is the method −
public static <T> Stream<T> convertIterator(Iterator<T> iterator) { return StreamSupport.stream(((Iterable) () -> iterator).spliterator(), false); }
Example
Following is the program to convert an Iterator to Stream in Java −
import java.util.stream.*; import java.util.*; public class Demo { public static <T> Stream<T> convertIterator(Iterator<T> iterator) { return StreamSupport.stream(((Iterable) () -> iterator).spliterator(), false); } public static void main(String[] args) { Iterator<Integer>iterator = Arrays.asList(50, 100, 200, 400, 500, 1000).iterator(); Stream<Integer>stream = convertIterator(iterator); System.out.println("Iterator to Stream..."); stream.forEach(s -> System.out.println(s)); } }
Output
Iterator to Stream... 50 100 200 400 500 1000
Advertisements