Create instance <T> instance from Iterator <T>
5 answers
I tend to Guava Lists.newArrayList(Iterator)
because I usually have Guava as a dependency and it already exists.
+14
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()); } }
It should be noted that if the iterator is not at the beginning of your structure, you have no way to get the previous elements.
If you have a collection from which to run the iterator, you can create a list using the constructor that takes the collection. ex: LinkedList
constructor:
LinkedList(Collection<? extends E> c)
0
This is a way to convert from a 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 + " "); }
0