Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to implement iterator on nested collection in Java?
    primarykey
    data
    text
    <p>I have a nested collection with this representation <code>Collection&lt;Collection&lt;T&gt;&gt;</code>. I have implemented the Iterator on the class, but the next() method is not giving the right results. It is fetching only the first element of each list. Example <code>List&lt;List&lt;String&gt;&gt;</code> and values are <code>{"1","2"},{"3","4"},{"5","6"}</code>. The Complete layout of class.</p> <pre><code>import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; public class NestedCollectionIterator implements Iterator&lt;Object&gt; { private Collection&lt;? extends Collection&lt;? extends Object&gt;&gt; _collOfColl = null; private Iterator&lt;? extends Collection&lt;? extends Object&gt;&gt; itCollection = null; private Iterator&lt;? extends Object&gt; innerIterator = null; Object next = null; public NestedCollectionIterator( Collection&lt;? extends Collection&lt;? extends Object&gt;&gt; collofColl){ _collOfColl = collofColl; itCollection = _collOfColl.iterator(); } @Override public boolean hasNext() { if(itCollection.hasNext()){ innerIterator = itCollection.next().iterator(); if(innerIterator != null || innerIterator.hasNext()){ next = innerIterator.next(); return true; } } return false; } public Object next() { if(hasNext()){ Object obj = next; //Need some changes here. return obj; } return null; } @Override public void remove() {} } </code></pre> <p>Class to test the implementation</p> <pre><code>class Sample{ public static void main(String[] args){ List&lt;List&lt;String&gt;&gt; Nestedlist = new ArrayList&lt;List&lt;String&gt;&gt;(); List&lt;String&gt; l = new ArrayList&lt;String&gt;(); l.add("1"); l.add("2"); Nestedlist.add(l); l = new ArrayList&lt;String&gt;(); l.add("3"); l.add("4"); Nestedlist.add(l); l = new ArrayList&lt;String&gt;(); l.add("5"); l.add("6"); Nestedlist.add(l); NestedCollectionIterator cc = new NestedCollectionIterator(Nestedlist); while(cc.hasNext()){ System.out.println(cc.next.toString()); } } } </code></pre> <p>the results is 1,3,5. How make the list iterate over all the elements in list first and then move to next collection item inside it?</p> <p>Thanks.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload