I want something like this:
public void CopyIteratorIntoList(Iterator<Foo> fooIterator) {
List<Foo> fooList = new ArrayList<Foo>();
fooList.addAll(fooIterator);
}
which should be equivalent to:
public void CopyIteratorIntoList(Iterator<Foo> fooIterator) {
List<Foo> fooList = new ArrayList<Foo>();
while(fooIterator.hasNext())
fooList.add(fooIterator.next());
}
Is there any method in the API to achieve that, or is this the only way?
No, there's nothing like that in the Standard API.
In Java, it's not idiomatic (and thus rather uncommon) to use Iterator
as part of an API; they're typically produced and immediately consumed.
No, but the Google Collections library has a nice way to do that (if you're going to be using some of it's other function - no reason to add that dependency just for that):
Iterators.addAll(targetCollection, sourceIterator);
In Guava (Google's new general-purpose Java library, which supersedes google-collections), this could be simply:
return Lists.newArrayList(fooIterator);
or if the List will be read-only:
return ImmutableList.copyOf(fooIterator);
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