- 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 Iterator to Iterable in Java
Let’s say the following is our Iterator with Integer values −
Iterator<Integer>iterator = Arrays.asList(20, 40, 60, 80, 100, 120, 150, 200).iterator();
Now, convert the Iterator to Iterable −
Iterable<Integer>iterable = StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, 0),false).collect(Collectors.toList());
Example
Following is the program to convert Iterator to Iterable in Java −
import java.util.*; import java.util.stream.Collectors; import java.util.stream.StreamSupport; public class Demo { public static void main(String[] args) { Iterator<Integer>iterator = Arrays.asList(20, 40, 60, 80, 100, 120, 150, 200).iterator(); Iterable<Integer>iterable = StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, 0), false).collect(Collectors.toList()); System.out.println("Iterable = "); iterable.forEach(System.out::println); } }
Output
Iterable = 20 40 60 80 100 120 150 200
Advertisements