Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Overview

In this tutorial, we’ll explore different ways to convert an Iterable to a Collection in Java.

We’ll start with plain Java solutions, then have a look at the options that the Guava and Apache Commons libraries also provide.

2. Iterable and Iterator

First, we’ll define our Iterable:

Iterable<String> iterable = Arrays.asList("john", "tom", "jane");

We’ll also define a simple Iterator – to highlight the difference between converting Iterable to Collection and Iterator to Collection:

Iterator<String> iterator = iterable.iterator();

3. Using Plain Java

3.1. Iterable to Collection

We can use the Java 8 forEach() method to add all elements to the List:

@Test
public void whenConvertIterableToListUsingJava8_thenSuccess() {
    List<String> result = new ArrayList<String>();
    iterable.forEach(result::add);

    assertThat(result, contains("john", "tom", "jane"));
}

Or use the Spliterator class to convert our Iterable to Stream then to Collection:

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

3.2. Iterator to Collection

On the other hand, instead of using forEach(), we’ll use forEachRemaining() with Iterator:

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

    assertThat(result, contains("john", "tom", "jane"));
}

We can also create a Spliterator from our Iterator then use it to convert Iterator to Stream:

List<String> result = 
  StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED), false)
    .collect(Collectors.toList());

3.3. Using a For-Loop

Let’s also have a look at a solution that uses a very simple for-loop to convert our Iterable to a List:

@Test
public void whenConvertIterableToListUsingJava_thenSuccess() {
    List<String> result = new ArrayList<String>();
    for (String str : iterable) {
        result.add(str);
    }

    assertThat(result, contains("john", "tom", "jane"));
}

On the other hand, we’ll use hasNext() and next() with the Iterator:

@Test
public void whenConvertIteratorToListUsingJava_thenSuccess() {
    List<String> result = new ArrayList<String>();
    while (iterator.hasNext()) {
        result.add(iterator.next());
    }

    assertThat(result, contains("john", "tom", "jane"));
}

4. Using Guava

There are also a few libraries available that provide convenient methods to help us achieve this.

Let’s see how we can use Guava to convert from an Iterable to a List:

We can create a new List from Iterable or Iterator using Lists.newArrayList():

List<String> result = Lists.newArrayList(iterable);

Or we can use ImmutableList.copyOf():

List<String> result = ImmutableList.copyOf(iterable);

5. Using Apache Commons

Finally, we’ll use Apache Commons IterableUtils to create a List from Iterable:

List<String> result = IterableUtils.toList(iterable);

Similarly, we’ll use IteratorUtils to create a List from our Iterator:

List<String> result = IteratorUtils.toList(iterator);

6. Conclusion

In this short article, we learned how to convert an Iterable and Iterator to a Collection using Java. We explored different ways using plain Java, and two external libraries: Guava and Apache Commons.

As always, the full source code is available over on GitHub.

Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.