AdBlock Detected

It looks like you're using an ad-blocker!

Our team work realy hard to produce quality content on this website and we noticed you have ad-blocking enabled. Advertisements and advertising enable us to continue working and provide high-quality content.

Convert an Iterator to a List in Java

In this new entry from Refactorizando, we are going to see how to convert an Iterator to a List in Java, using traditional methods, Streams, and additional libraries such as Guava and Apache Commons. We have previously explored the Java Streams API in another article, which you can see here.

For all the examples we are going to explain, we will start with the following data:

Iterator<String> iterator = Arrays.asList("Orange", "Blue", "Green").iterator();

Convert Iterator to List with While Loop

The most traditional and perhaps well-known way to transform an Iterator to a List is by using a while loop. By using the hasNext() method, we can determine the end of the iterator and exit the loop.

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

Convert Iterator to List with Java Streams

To convert any Iterator object to a List using the Java Streams API, we can utilize StreamSupport. It provides methods to manipulate and convert streams.

List<String> actualList = StreamSupport.stream(
           Spliterators.spliteratorUnknownSize(iterator, 0), false)
               .collect(Collectors.toList());

Convert Iterator to List using forEachRemaining

forEachRemaining is a method introduced in Java 8 that allows us to modify and build our list. With this method, which can be considered as a “for loop,” each element is processed until there are no more elements.

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

Convert Iterator to List with Guava

Guava is a set of open-source libraries written for Java and maintained and developed by Google. Among these libraries, there are some that facilitate working with collections in Java.

To use this library, you need to add the following dependency to your pom.xml:

<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>30.1-jre</version>
</dependency>

or with Gradle:

compile group: 'com.google.guava', name: 'guava', version: '30.1-jre'

This library allows us to transform an iterator to an immutable or mutable list. Let’s see an example:

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

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

Convert Iterator to List with Apache Commons

Now let’s talk about the well-known and long-standing Apache Commons library, which helps us work with collections in Java and reduces boilerplate code.

To use this library, you need to add the following dependency to your pom.xml:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-collections4</artifactId>
    <version>4.4</version>
</dependency>

Or if you are working with Gradle:





compile group: 'org.apache.commons', name: 'commons-collections4', version: '4.4'

To transform an Iterator to a List, we can use IteratorUtils, which performs the direct transformation:

List<String> actualList = IteratorUtils.toList(iterator);
assertEquals(actualList, auxList);

Examples with Tests

Here are all the examples with corresponding tests:

public class IteratorExamples{

    Iterator<String> iterator = Arrays.asList("Orange", "Blue", "Green").iterator();

    List<String> auxList = List.of("Orange", "Blue", "Green");
    @Test
    public void transformToListWithWhile() {
       List<String> actualList = new ArrayList<>();
       while (iterator.hasNext()) {
          actualList.add(iterator.next());
       }

       assertEquals(actualList, auxList);
    }

    @Test
   public void transformToListWithAPIStream() {

   List<String> actualList = StreamSupport.stream(
           Spliterators.spliteratorUnknownSize(iterator, 0), false)
               .collect(Collectors.toList());


        assertEquals(actualList, auxList);
    }

    @Test
    public void transformToListWithInmutableGuava() {
       List<String> actualList = ImmutableList.copyOf(iterator);

        assertEquals(actualList, auxList);
    }

    @Test
    public void transformToListWithMutableGuava() {
       List<String> actualList = Lists.newArrayList(iterator);
        assertEquals(actualList, auxList);

    }

    @Test
    public void transformToListWithApacheCommons() {
       List<String> actualList = IteratorUtils.toList(iterator);
        assertEquals(actualList, auxList);

    }

   @Test
    public void transformToListWithForEachRemaining() {
       List<String> actualList = new ArrayList<>();
       iterator.forEachRemaining(actualList::add);
    }

}

Conclusion

As we have seen in this article on how to convert an Iterator to a List in Java, there are different ways to perform transformations on collections using different libraries.

Leave a Reply

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