Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an easy way to copy an iterator into a list in Java?

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?

like image 380
Björn Pollex Avatar asked May 10 '10 11:05

Björn Pollex


3 Answers

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.

like image 84
Michael Borgwardt Avatar answered Sep 21 '22 14:09

Michael Borgwardt


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);
like image 37
Carl Avatar answered Sep 20 '22 14:09

Carl


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);
like image 39
Cowan Avatar answered Sep 18 '22 14:09

Cowan