Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create List<T> instance from Iterator<T>

Anyone know if there is a standard way to create a List from an Iterator instance?

like image 868
BillMan Avatar asked Jun 13 '12 15:06

BillMan


People also ask

Can Iterator be used for list?

An iterator is an object in Java that allows iterating over elements of a collection. Each element in the list can be accessed using iterator with a while loop.

Can you add to a list while iterating Java?

You can't modify a Collection while iterating over it using an Iterator , except for Iterator.

Can we use list Iterator for ArrayList?

In Java, ListIterator is an interface in Collection API. It extends Iterator interface. To support Forward and Backward Direction iteration and CRUD operations, it has the following methods. We can use this Iterator for all List implemented classes like ArrayList, CopyOnWriteArrayList, LinkedList, Stack, Vector, etc.


1 Answers

Use the Iterator to get every element and add it to a List.

List<String> list = new LinkedList<String>();

while(iter.hasNext()) { // iter is of type Iterator<String>
    list.add(iter.next());
}
like image 102
tskuzzy Avatar answered Oct 13 '22 17:10

tskuzzy