Convert Iterator to Collection

1. Overview

In this article I will write about converting an Iterator to Collection. Let us begin.

Embed from Getty Images

2. Content

Below are few ways for converting Iterator to a Collection.

2.1. Prior to Java 8

Assume that if you call a method which returns you an Iterator and now you want to use this Iterator to pull data from underlying collection and convert it to a new Collection. Prior to Java 8 we would do something like this:

Iterator<String> iterator = doSomething();
List<String> result = new ArrayList<>();
while(iterator.hasNext()) {
    result.add(iterator.next());
}

2.2. Using forEachRemaining()

Is there a better way to do this task? Yes we can do that. Iterator interface has a new method called forEachRemaining added in Java 8. Let us use that method.

Iterator<String> iterator = doSomething();
List<String> result = new ArrayList<>();
iterator.forEachRemaining(new Consumer<String>() {
    @Override
        public void accept(String element) {
            result.add(element);
    }
});

2.3. Using Lambda Expression

Nice. Can we do better than this? As Consumer interface is a functional interface we can use lambda expression to replace the above code as follows:

Iterator<String> iterator = doSomething();
List<String> result = new ArrayList<>();
iterator.forEachRemaining(element -> result.add(element));

2.4. Using Method Reference

Excellent. Can we still do better? We can replace the lambda expression with method reference.

Iterator<String> iterator = doSomething();
List<String> result = new ArrayList<>();
iterator.forEachRemaining(result::add);

Awesome. So we used a new Java 8 method of Iterator interface to convert Iterator to Collection.

3. Conclusion

In this article, we explored 4 different ways to convert Iterator to Collection.

Join the Newsletter

Download Complete Guide to Comparators in
1. Java 8
2. Map.Entry Interface
3. Spring
4. Google Guava
5. Apache Collections
with more than 60 examples. One book to know and learn it all.

    We respect your privacy. Unsubscribe at any time.

    Leave a Reply

    Your email address will not be published. Required fields are marked *