Often there is the need to setup an ArrayList<>. One of the constructors takes a collection, but there is no constructor that takes an iterator.
What if I have an iterator? Is there a way to “reach up” to the collection that offers the iterator in order to use the ArrayList<> constructor?
Specifically I have the iterator offered by PropertiesConfiguration.getKeys() which is part of org.apache.commons.
There’s no such thing, an
Iterator‘sCollection. An Iterator can be created independently of aCollection. It can be obtained from anyIterable, or you can even create a class implementing an iterator.However, you can obtain an
ArrayListfrom anIteratorby iterating it and adding its elements one by one:Note, however, that this cannot be done reliably for every possible iterator, since there’s the possibility that an iterator will iterate forever, thus causing an infinite loop and most probably an
OutOfMemoryError.I’d suggest you take a look at Google Guava, an utility library from Google. It has a class called Lists, which allows you to do the following:
The library has tons of methods extremely useful for everyday Java coding. It contains mostly everything you want but cannot find in the standard Java 6 API.