- 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 a List in Java
Let’s say the following is our Iterator with Integer values −
Iterator<Integer> iterator = Arrays.asList(50, 100, 200, 300, 400, 500, 1000).iterator();
Now, convert this Iterator to a List −
List<Integer> myList = new ArrayList<>(); iterator.forEachRemaining(myList::add);
Example
Following is the program to convert an Iterator to a List in Java −
import java.util.*; public class Demo { public static void main(String[] args){ Iterator<Integer> iterator = Arrays.asList(50, 100, 200, 300, 400, 500, 1000).iterator(); List<Integer> myList = new ArrayList<>(); iterator.forEachRemaining(myList::add); System.out.println("Iterator to list = "+myList); } }
Output
Iterator to list = [50, 100, 200, 300, 400, 500, 1000]
Advertisements