In my application, I use a third-party library (Spring Data for MongoDB), which returns Iterable<T>
, but the rest of my code expects Collection<T>
.
Is there a utility method in Java to quickly java iterable to list conversion, avoiding multiple for-each
loops?
The first approach works well, but if you want something more functional and optimized for large datasets, StreamSupport is a great option:
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
public static <T> List<T> convertIterableToList(Iterable<T> iterable) {
return StreamSupport.stream(iterable.spliterator(), false)
.collect(Collectors.toList());
}
Why use this?
The spliterator() method efficiently turns the Iterable into a Stream, and collect(Collectors.toList()) does the rest.
This is a great approach, especially if parallel processing is a potential need—just replace false with true in stream(iterable.spliterator(), false).
If you’re working with Java 8 or newer, a simple way to convert an Iterable into a List is by leveraging forEach. Here’s how:
public static <T> List<T> convertIterableToList(Iterable<T> iterable) {
List<T> list = new ArrayList<>();
iterable.forEach(list::add);
return list;
}
This method is clean, easy to understand, and works well when performance is not a critical concern. If your dataset is small to medium-sized, this is a solid choice.
The previous solutions are solid, but if you’re already using Google Guava, you can do it in one line:
import com.google.common.collect.Lists;
List<T> list = Lists.newArrayList(iterable);
This is probably the cleanest solution—just call Lists.newArrayList(), and you’re done. Guava optimizes these utilities, making them reliable and performant.