Anyone know if there is a standard way to create a List from an Iterator instance?
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.
You can't modify a Collection while iterating over it using an Iterator , except for Iterator.
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.
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());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With