BillMan
BillMan

Reputation: 9924

Create List<T> instance from Iterator<T>

Anyone know if there is a standard way to create a List from an Iterator instance?

Upvotes: 12

Views: 12819

Answers (6)

davidxxx
davidxxx

Reputation: 131346

In Java 8 you can use these ways (while verbose enough):

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

or

Iterator<String> iterator = ...;
List<String> list = new ArrayList<>(); // or LinkedList() if more relevant (adding being faster for LinkedList)
iterator.forEachRemaining(list::add);

Upvotes: 4

dnc253
dnc253

Reputation: 40337

I had this need, and as a user of Apache Commons, this is what I did:

IteratorUtils.toList(iterator);

Javadoc here: https://commons.apache.org/proper/commons-collections/javadocs/api-3.2.2/org/apache/commons/collections/IteratorUtils.html#toList(java.util.Iterator)

Upvotes: 5

Dave Newton
Dave Newton

Reputation: 160191

I tend towards Guava's Lists.newArrayList(Iterator) because I generally have Guava as a dependency, and it already exists.

Upvotes: 14

Trevor Mack
Trevor Mack

Reputation: 155

This is the way that I convert from List to Iterator and vice versa.

ArrayList arrayList = new ArrayList(); 
// add elements to the array list 
arrayList.add("C"); 
arrayList.add("A"); 
arrayList.add("E"); 
arrayList.add("B"); 
arrayList.add("D"); 
arrayList.add("F"); 

// use iterator to display contents of arrayList
System.out.print("Original contents of arrayList: "); 
Iterator iterator = arrayList.iterator(); 
ArrayList arrayList2 = new ArrayList();

while(iterator.hasNext()) {

    Object element = iterator.next(); 
    arrayList2.add(element);
    System.out.print(element + " ");

} 

Upvotes: 1

Colin D
Colin D

Reputation: 5661

try something like the following:

public T List<T> listFromIterator(Iterator<T> iterator) {

List<T> result = new LinkedList<T>();
  while(iterator.hasNext()) {
    result.add(iterator.next());
  }

}

One thing to note is that if the iterator is not at the beginning of your structure, you have no way of retrieving previous elements.

If you have the collection that the iterator is from, you can create a list by using a constructor that takes a collection. ex: the LinkedList constructor:

LinkedList(Collection<? extends E> c) 

Upvotes: 2

tskuzzy
tskuzzy

Reputation: 36456

Use the Iterator to get every element and add it to a List.

List<String> list = new LinkedList<String>();

while(iter.hasNext()) { // iter is of type Iterator<String>
    list.add(iter.next());
}

Upvotes: 5

Related Questions