An Iterator
is a computer programming concept that implies the behavior of being able to traverse a container, particularly ArrayList. Depending on your situation you may want to convert the Iterator
back to a List
. This example will show how to convert from an Iterator
to an Arraylist
using java, java 8, guava and apache commons.
Setup
static LinkedList<String> collection = new LinkedList<String>();
static {
collection.push("One");
collection.push("Two");
collection.push("Three");
collection.push("Four");
}
Straight up Java
@Test
public void convert_iterator_to_list_java() {
Iterator<String> iteratorToList = collection.iterator();
List<String> listOfStrings = new ArrayList<String>(4);
while (iteratorToList.hasNext()) {
listOfStrings.add(iteratorToList.next());
}
assertTrue(listOfStrings.size() == 4);
}
Java 8
@Test
public void convert_iterator_to_list_java8() {
Iterator<String> iteratorToCollection = collection.iterator();
List<String> convertedIterator = StreamSupport.stream(
Spliterators.spliteratorUnknownSize(iteratorToCollection,
Spliterator.ORDERED), false).collect(
Collectors.<String> toList());
assertTrue(convertedIterator.size() == 4);
}
Google Guava
@Test
public void convert_iterator_to_list_guava() {
Iterator<String> iteratorToArray = collection.iterator();
List<String> convertedIterator = Lists.newArrayList(iteratorToArray);
assertTrue(convertedIterator.size() == 4);
}
Apache Commons
@Test
public void convert_iterator_to_list_apache() {
Iterator<String> iteratorToArrayList = collection.iterator();
@SuppressWarnings("unchecked")
List<String> convertedIteratorToList = IteratorUtils
.toList(iteratorToArrayList);
assertTrue(convertedIteratorToList.size() == 4);
}