Java Top

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE

1. Overview

In this short tutorial, we’ll learn how to convert an Iterator to a List in Java. We’ll cover a few examples using a while loop, Java 8, and a few common libraries.

We’ll use an Iterator with Integers for all our examples:

Iterator<Integer> iterator = Arrays.asList(1, 2, 3).iterator();

2. Using a While Loop

Let’s begin with the approach traditionally used before Java 8. We’ll convert the Iterator to a List using a while loop:

List<Integer> actualList = new ArrayList<Integer>();
while (iterator.hasNext()) {
    actualList.add(iterator.next());
}

assertThat(actualList, containsInAnyOrder(1, 2, 3));

3. Using Java 8 Iterator.forEachRemaining

In Java 8 and later, we can use the Iterator‘s forEachRemaining() method to build our List. We’ll pass the add() method of the List interface as a method reference:

List<Integer> actualList = new ArrayList<Integer>();
iterator.forEachRemaining(actualList::add);

assertThat(actualList, containsInAnyOrder(1, 2, 3));

4. Using the Java 8 Streams API

Next, we’ll use the Java 8 Streams API to convert the Iterator to a List. In order to use the Stream API, we need to first convert the Iterator to an Iterable. We can do this using Java 8 Lambda expressions:

Iterable<Integer> iterable = () -> iterator;

Now, we can use the StreamSupport class’ stream() and collect() methods to build the List:

List<Integer> actualList = StreamSupport
  .stream(iterable.spliterator(), false)
  .collect(Collectors.toList());

assertThat(actualList, containsInAnyOrder(1, 2, 3));

5. Using Guava

The Guava library from Google provides options to create both a mutable and immutable Lists, so we’ll see both approaches.

Let’s first create an immutable List using ImmutableList.copyOf() method:

List<Integer> actualList = ImmutableList.copyOf(iterator);

assertThat(actualList, containsInAnyOrder(1, 2, 3));

Now, let’s create a mutable List using Lists.newArrayList() method:

List<Integer> actualList = Lists.newArrayList(iterator);

assertThat(actualList, containsInAnyOrder(1, 2, 3));

6. Using Apache Commons

The Apache Commons Collections library provides options to work on a List. We’ll use IteratorUtils to do the conversion:

List<Integer> actualList = IteratorUtils.toList(iterator);

assertThat(actualList, containsInAnyOrder(1, 2, 3));

7. Conclusion

In this article, we’ve covered a few options for converting an Iterator to a List. While there are a few other ways of achieving this, we’ve covered several commonly used options.

The implementation of all these examples and code snippets can be found over on GitHub.

Java bottom

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE

Leave a Reply

avatar
  Subscribe  
Notify of