views:

86

answers:

4

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?

+11  A: 

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.

Michael Borgwardt
+3  A: 

I do not believe that iterators are guaranteed to halt after a fixed number of iterations, so this probably isn't a safe way to insert data into your list. Consider a dummy iterator implementation which always returns the constant 42 from calls to next(). Your application will quickly run out of memory.

Stefan Kendall
+5  A: 

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);
Carl
+3  A: 

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);
Cowan
Or, indeed, Iterators.addAll (as suggested by Carl) if you want to add to an existing collection.
Cowan