Create instance <T> instance from Iterator <T>

Does anyone know if there is a standard way to create a list from an Iterator instance?

+6
source share
5 answers

I tend to Guava Lists.newArrayList(Iterator) because I usually have Guava as a dependency and it already exists.

+14
source

I had this need, and as an Apache Commons user, 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)

+5
source

Use Iterator to get each item and add it to the List .

 List<String> list = new LinkedList<String>(); while(iter.hasNext()) { // iter is of type Iterator<String> list.add(iter.next()); } 
+3
source

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
source

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
source

Source: https://habr.com/ru/post/917991/


All Articles