Can we write our own iterator in Java? - java

If I have a list containing [alice, bob, abigail, charlie] and I want to write an iterator such that it iterates over elements that begin with 'a', can I write my own ? How can I do that ?

The best reusable option is to implement the interface Iterable and override the method iterator().
Here's an example of a an ArrayList like class implementing the interface, in which you override the method Iterator().
import java.util.Iterator;
public class SOList<Type> implements Iterable<Type> {
private Type[] arrayList;
private int currentSize;
public SOList(Type[] newArray) {
this.arrayList = newArray;
this.currentSize = arrayList.length;
}
#Override
public Iterator<Type> iterator() {
Iterator<Type> it = new Iterator<Type>() {
private int currentIndex = 0;
#Override
public boolean hasNext() {
return currentIndex < currentSize && arrayList[currentIndex] != null;
}
#Override
public Type next() {
return arrayList[currentIndex++];
}
#Override
public void remove() {
throw new UnsupportedOperationException();
}
};
return it;
}
}
This class implements the Iterable interface using Generics. Considering you have elements to the array, you will be able to get an instance of an Iterator, which is the needed instance used by the "foreach" loop, for instance.
You can just create an anonymous instance of the iterator without creating extending Iterator and take advantage of the value of currentSize to verify up to where you can navigate over the array (let's say you created an array with capacity of 10, but you have only 2 elements at 0 and 1). The instance will have its owner counter of where it is and all you need to do is to play with hasNext(), which verifies if the current value is not null, and the next(), which will return the instance of your currentIndex. Below is an example of using this API...
public static void main(String[] args) {
// create an array of type Integer
Integer[] numbers = new Integer[]{1, 2, 3, 4, 5};
// create your list and hold the values.
SOList<Integer> stackOverflowList = new SOList<Integer>(numbers);
// Since our class SOList is an instance of Iterable, then we can use it on a foreach loop
for(Integer num : stackOverflowList) {
System.out.print(num);
}
// creating an array of Strings
String[] languages = new String[]{"C", "C++", "Java", "Python", "Scala"};
// create your list and hold the values using the same list implementation.
SOList<String> languagesList = new SOList<String>(languages);
System.out.println("");
// Since our class SOList is an instance of Iterable, then we can use it on a foreach loop
for(String lang : languagesList) {
System.out.println(lang);
}
}
// will print "12345
//C
//C++
//Java
//Python
//Scala
If you want, you can iterate over it as well using the Iterator instance:
// navigating the iterator
while (allNumbers.hasNext()) {
Integer value = allNumbers.next();
if (allNumbers.hasNext()) {
System.out.print(value + ", ");
} else {
System.out.print(value);
}
}
// will print 1, 2, 3, 4, 5
The foreach documentation is located at http://download.oracle.com/javase/1,5.0/docs/guide/language/foreach.html. You can take a look at a more complete implementation at my personal practice google code.
Now, to get the effects of what you need I think you need to plug a concept of a filter in the Iterator... Since the iterator depends on the next values, it would be hard to return true on hasNext(), and then filter the next() implementation with a value that does not start with a char "a" for instance. I think you need to play around with a secondary Interator based on a filtered list with the values with the given filter.

Sure. An iterator is just an implementation of the java.util.Iterator interface. If you're using an existing iterable object (say, a LinkedList) from java.util, you'll need to either subclass it and override its iterator function so that you return your own, or provide a means of wrapping a standard iterator in your special Iterator instance (which has the advantage of being more broadly used), etc.

Good example for Iterable to compute factorial
FactorialIterable fi = new FactorialIterable(10);
Iterator<Integer> iterator = fi.iterator();
while (iterator.hasNext()){
System.out.println(iterator.next());
}
Short code for Java 1.8
new FactorialIterable(5).forEach(System.out::println);
Custom Iterable class
public class FactorialIterable implements Iterable<Integer> {
private final FactorialIterator factorialIterator;
public FactorialIterable(Integer value) {
factorialIterator = new FactorialIterator(value);
}
#Override
public Iterator<Integer> iterator() {
return factorialIterator;
}
#Override
public void forEach(Consumer<? super Integer> action) {
Objects.requireNonNull(action);
Integer last = 0;
for (Integer t : this) {
last = t;
}
action.accept(last);
}
}
Custom Iterator class
public class FactorialIterator implements Iterator<Integer> {
private final Integer mNumber;
private Integer mPosition;
private Integer mFactorial;
public FactorialIterator(Integer number) {
this.mNumber = number;
this.mPosition = 1;
this.mFactorial = 1;
}
#Override
public boolean hasNext() {
return mPosition <= mNumber;
}
#Override
public Integer next() {
if (!hasNext())
return 0;
mFactorial = mFactorial * mPosition;
mPosition++;
return mFactorial;
}
}

This is the complete code to write an iterator such that it iterates over elements that begin with 'a':
import java.util.Iterator;
public class AppDemo {
public static void main(String args[]) {
Bag<String> bag1 = new Bag<>();
bag1.add("alice");
bag1.add("bob");
bag1.add("abigail");
bag1.add("charlie");
for (Iterator<String> it1 = bag1.iterator(); it1.hasNext();) {
String s = it1.next();
if (s != null)
System.out.println(s);
}
}
}
Custom Iterator class
import java.util.ArrayList;
import java.util.Iterator;
public class Bag<T> {
private ArrayList<T> data;
public Bag() {
data = new ArrayList<>();
}
public void add(T e) {
data.add(e);
}
public Iterator<T> iterator() {
return new BagIterator();
}
public class BagIterator<T> implements Iterator<T> {
private int index;
private String str;
public BagIterator() {
index = 0;
}
#Override
public boolean hasNext() {
return index < data.size();
}
#Override
public T next() {
str = (String) data.get(index);
if (str.startsWith("a"))
return (T) data.get(index++);
index++;
return null;
}
}
}

You can implement your own Iterator. Your iterator could be constructed to wrap the Iterator returned by the List, or you could keep a cursor and use the List's get(int index) method. You just have to add logic to your Iterator's next method AND the hasNext method to take into account your filtering criteria. You will also have to decide if your iterator will support the remove operation.

Here is the complete answer to the question.
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
class ListIterator implements Iterator<String>{
List<String> list;
int pos = 0;
public ListIterator(List<String> list) {
this.list = list;
}
#Override
public boolean hasNext() {
while(pos < list.size()){
if (list.get(pos).startsWith("a"))
return true;
pos++;
}
return false;
}
#Override
public String next() {
if (hasNext())
return list.get(pos++);
throw new NoSuchElementException();
}
}
public class IteratorTest {
public static void main(String[] args) {
List<String> list = Arrays.asList("alice", "bob", "abigail", "charlie");
ListIterator itr = new ListIterator(list);
while(itr.hasNext())
System.out.println(itr.next()); // prints alice, abigail
}
}
ListIterator is the iterator for the array which returns the elements that start with 'a'.
There is no need for implementing an Iterable interface. But that is a possibility.
There is no need to implement this generically.
It fully satisfies the contract for hasNext() and next(). ie if hasNext() says there are still elements, next() will return those elements. And if hasNext() says no more elements, it returns a valid NoSuchElementException exception.

Related

making a list that maintains a reverse order by its own

I've been tasked with the following question: create a collection ReverseList that would implement List. by iterating over an object list of type ReverseList with a for loop (for(E e:list)) we would get the items in an order reversed of what they were entered.
implement the following class while extending from ArrayList
so essentially I need to create a collection that doesnt follow the natural ordering of insertion
let me clarify that i am not looking to reverse the list after its creation and adding items with something like Collections.reverse() but rather have the list maintain its own order
what I've tried so far is making a custom Iterator. however for some reason when trying to iterate over the list im getting thrown out with an IndexOutOfBoundsException (even though the list isnt empty)
my code:
public class ReverseList<E> extends ArrayList<E> implements List<E>{
private class ReverseIterator<E> extends ReverseList<E> implements Iterator<E>
{
private int pos;
public ReverseIterator()
{
pos = super.size()-1;
}
public ReverseIterator(ReverseList<E> r)
{
pos = r.size()-1;
}
#Override
public boolean hasNext() {
return pos >= 0;
}
#Override
public E next() {
return super.get(pos--);
}
}
#Override
public Iterator<E> iterator() {
// TODO Auto-generated method stub
return new ReverseIterator<E>(this);
}
public static void main(String[] args)
{
ReverseList<Integer> r = new ReverseList<>();
r.add(new Integer(1));
r.add(new Integer(2));
r.add(new Integer(3));
r.add(new Integer(4));
for(Integer i:r)
{
System.out.println(i);
}
}
}
error thrown: Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 3 out of bounds for length 0 ( thrown at the for loop )
why is the list at length 0?
is my approach even possible? is there a better way to do it?
Your ReverseIterator is a subclass of ReverseList. This means, it is a list on its own. Then, you are mixing up the state of these two lists. In the ReverseIterator(ReverseList<E> r), you use r’s size to initialize pos, in next() you use super.get(pos--), accessing the other list’s content. This other list is always empty.
An iterator should never be a collection. When you implement an iterator as an inner class, you can access the outer collection’s state implicitly.
Besides that, your list clearly violates the contract of the List interface and will cause a lot of other problems in the future, as its iterator() is inconsistent with other List features, like all index based operations or listIterator().
You should not change the fundamentals of a class, just for the sake of a single operation (i.e. iterate backwards). Rather, implement this single operation as a distinct operation.
For example:
public class ReversibleList<T> extends ArrayList<T> {
private class ReverseIterator implements Iterator<T> {
private int pos = size() - 1;
#Override
public boolean hasNext() {
return pos >= 0;
}
#Override
public T next() {
return get(pos--);
}
}
public Iterable<T> reverse() {
return () -> new ReverseIterator();
}
public static void main(String[] args) {
ReversibleList<Integer> r = new ReversibleList<>();
r.add(1);
r.add(2);
r.add(3);
r.add(4);
for(Integer i: r.reverse()) {
System.out.println(i);
}
}
}
The reverse() view has no storage of its own but always reflects the current contents of the list, in reverse order. The original List keeps fulfilling its contract.
Note that it is possible to create reversed view to a list supporting other operations of the List interface beyond iterator():
public class ReversibleList<T> extends ArrayList<T> {
private class ReversedList extends AbstractList<T> implements RandomAccess {
#Override
public T get(int index) {
return ReversibleList.this.get(size() - index - 1);
}
#Override
public int size() {
return ReversibleList.this.size();
}
}
public List<T> reverse() {
return new ReversedList();
}
public static void main(String[] args) {
ReversibleList<Integer> r = new ReversibleList<>();
r.add(1);
r.add(2);
r.add(3);
r.add(4);
r.reverse().subList(1, 4).stream().forEach(System.out::println);
}
}

Implementer Iterator

I am currently trying to implement Iterator which receives a collection and a char and that yields the
Strings that starts with that char.
So I ended up with the following (working) code:
class A {
public static void main (String [] args) {
String [] arr = {"abcd","gr","gres","bvg","bb"};
class FirstCharIt implements Iterator<String> {
char c;
private Iterator<String> it;
public FirstCharIt (Collection<String> lst,char c) {
this.c = c;
this.it = lst.stream().filter(x->{
return (x.charAt(0)==this.c);
}).iterator();
}
#Override
public boolean hasNext() {
return it.hasNext();
}
#Override
public String next() {
return it.next();
}
public Iterator<String> get () {
return it;
}
}
FirstCharIt it1 = new FirstCharIt(Arrays.asList(arr),'b');
for (it1.get();it1.hasNext();) {
System.out.println(it1.next());
}
}
}
Although this code is working this is not actually implementing Iterator interface and I even can remove the 'implements Iterator' from my class headline.
And of course the method get wasn't there in more right implementation
So I would like to have some advice about what I did here,
thanks
Filter the input list at initialization, have that filtered collection and an index as fields of your iterator.
Have hasNext() check if the index has reached the end of the filtered collection, and next() increase the index and return the element it previously pointed at.
static class FirstCharIt implements Iterator<String> {
private int currentIndex;
private List<String> filtered;
public FirstCharIt (List<String> coll, char letter) {
this.filtered = coll.stream().filter(x->x.startsWith(""+letter)).collect(Collectors.toList());
this.currentIndex = 0;
}
#Override
public boolean hasNext() {
return currentIndex < filtered.size();
}
#Override
public String next() {
if (!hasNext()) { throw new NoSuchElementException(); }
return filtered.get(currentIndex++);
}
}
You can try it here.

Iterator and iterable for an 2D array Java

I have created two iterators for an array: the first runs the array by rows (iteratorRow) and then by columns and the second, first by columns and then by rows (iteratorColumn).
I have another class, Matrix, in which I must create two methods for performing iteration (iteratorRowColumn and iteratorColumnRow) that return iterators that have created to be accessible to other classes.
The array must implement the Iterable interface and may be configured (using a Boolean) which of the two iterators it shall be refunded by calling iterator () method.
How can I do that? Do I have to do some getters methods? Something like this?
public Iterator iteratorRowColumn () {
return new iteratorRow;
}
I think that the last sentence of assignment explains a problem very well. I am not sure what part of it is unclear so let me explain in detail:
The array must implement the Iterable interface
public class Matrix<T> implements Iterable<T>
may be configured (using a Boolean)
public Matrix(boolean defaultRowColumnIterator) {
this.defaultRowColumnIterator = defaultRowColumnIterator;
}
which of the two iterators it shall be returning by calling iterator() method
#Override
public Iterator<T> iterator() {
return defaultRowColumnIterator ? iteratorRowColumn() : iteratorColumnRow();
}
Here is a compilable example:
public class Matrix<T> implements Iterable<T> {
T[][] array;
boolean defaultRowColumnIterator;
public Matrix(boolean defaultRowColumnIterator) {
this.defaultRowColumnIterator = defaultRowColumnIterator;
}
// other methods and constructors
public Iterator<T> iteratorRowColumn() {
return null; // your current implementation
}
public Iterator<T> iteratorColumnRow() {
return null; // your current implementation
}
#Override
public Iterator<T> iterator() {
return defaultRowColumnIterator ? iteratorRowColumn() : iteratorColumnRow();
}
}
Something like this:
public class Proba {
Integer[][] array = new Integer[10][10];
public class MyIter implements Iterator<Integer> {
private Integer[] integers;
private int index = 0;;
public MyIter(Integer[] integers) {
this.integers = integers;
}
#Override
public boolean hasNext() {
return index < integers.length -1 ;
}
#Override
public Integer next() {
return integers[index];
}
#Override
public void remove() {
//TODO: remove
}
}
public static void main(String[] args) {
Iterator<Integer> iter = new Proba().getIterator(1);
while (iter.hasNext()) {
System.out.println(iter.next());
}
}
public Iterator<Integer> getIterator(int row) {
return new MyIter(array[row]);
}
}

Java list best practice

I need some container to keep elements so, if I'll try to get the size()+i element, i'll get element number i. Or with iterator, which starts from the beginning of container after it tries to get the last element? What are the best practicies in both cases? I mean performance and easy useability.
You could create a simple subclass of ArrayList<T> and override the get(int n) method as follows:
public T get(int n)
{
return super.get(n % this.size());
}
As to the iterator, you will need to implement your own, which shouldn't be all that hard.
EDIT:
Assuming your new class is called RingList, here's a sample RingIterator (untested):
public class RingIterator<T> implements Iterator<T>
{
private int cur = 0;
private RingList<T> coll = null;
protected RingIterator(RingList<T> coll) { this.coll = coll; }
public boolean hasNext() { return size() > 0; }
public T next()
{
if (!hasNext())
throw new NoSuchElementException();
int i=cur++;
cur=cur%size();
return coll.get(i);
}
public void remove() { throw new UnsupportedOperationException(); }
}
You would then override the iterator() method in RingList<T> as
public Iterator<T> iterator()
{
return new RingIterator(this);
}
For the first part, just ask for n % list.size() perhaps?
For the iterator part, create a class that wraps an iterator, and when next() returns null, just have it reset the iterator.
Thanks everyone, thats what I've created:
public class RingIterator<E> {
private List<E> _lst;
private ListIterator<E> _lstIter;
public RingIterator(ListIterator<E> iter, List<E> lst) {
super();
_lstIter = iter;
_lst = lst;
}
public E next() {
if(!_lstIter.hasNext())
_lstIter = _lst.listIterator();
return _lstIter.next();
}
public E previous() {
if(!_lstIter.hasPrevious())
_lstIter = _lst.listIterator(_lst.size());
return _lstIter.previous();
}
}
Then get method:
/*
* Returns ring iterator,
* use it with 'ParentClass' type.
*/
public RingIterator<SubClass> getRingIter(int i) {
return new RingIterator(_subs.listIterator(i),_subs);
}
And I use it:
RingIterator<SubClass> ri = _logic.getRingIter(1);
ParentClass ai = ri.next();
I wanted to make only type ParentClass (not SubClass) available via getRingIter, but I don't see a way to do it with no creation of List - convertion of List.
Extend the ArrayList class and implement the get(Integer) method the way you like. I think this is the 'best practice'.

Interview: Design an iterator for a collection of collections

Design an iterator for a collection of collections in java. The iterator should hide the nesting, allowing you to iterate all of the elements belonging to all of the collections as if you were working with a single collection
This is an old question, but nowadays (2019) we have JDK8+ goodies. In particular, we have streams, which make this task straightforward:
public static <T> Iterator<T> flatIterator(Collection<Collection<T>> collections) {
return collections.stream()
.filter(Objects::nonNull)
.flatMap(Collection::stream)
.iterator();
}
I'm filtering null inner collections out, just in case...
EDIT: If you also want to filter null elements out of the inner collections, just add an extra non-null filter aflter flatMap:
return collections.stream()
.filter(Objects::nonNull)
.flatMap(Collection::stream)
.filter(Objects::nonNull)
.iterator();
Here is a possible implementation. Note that I left remove() unimplemented:
public class MultiIterator <T> implements Iterator<T>{
private Iterator<? extends Collection<T>> it;
private Iterator<T> innerIt;
private T next;
private boolean hasNext = true;
public MultiIterator(Collection<? extends Collection<T>> collections) {
it = collections.iterator();
prepareNext();
}
private void prepareNext() {
do {
if (innerIt == null || !innerIt.hasNext()) {
if (!it.hasNext()) {
hasNext = false;
return;
} else
innerIt = it.next().iterator();
}
} while (!innerIt.hasNext());
next = innerIt.next();
}
#Override
public boolean hasNext() {
return hasNext;
}
#Override
public T next() {
if (!hasNext)
throw new NoSuchElementException();
T res = next;
prepareNext();
return res;
}
#Override
public void remove() {
//TODO
}
}
In this post you can see two implementations, the only (minor) difference is that it takes an iterator of iterators instead of a collection of collections.
This difference combined with the requirement to iterate the elements in a round-robin fashion (a requirement that wasn't requested by the OP in this question) adds the overhead of copying the iterators into a list.
The first approach is lazy: it will iterate an element only when this element is requested, the 'price' we have to pay is that the code is more complex because it needs to handle more edge-cases:
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.NoSuchElementException;
public class MultiIterator<E> implements Iterator {
List<Iterator<E>> iterators = new LinkedList<>();
Iterator<E> current = null;
public MultiIterator(Iterator<Iterator<E>> iterator) {
// copy the iterators into a list
while (iterator.hasNext()) {
iterators.add(iterator.next());
}
}
#Override
public boolean hasNext() {
boolean result = false;
if (iterators.isEmpty() && (current == null || !current.hasNext())) {
return false;
}
if (current == null) {
current = iterators.remove(0);
}
while (!current.hasNext() && !iterators.isEmpty()) {
current = iterators.remove(0);
}
if (current.hasNext()) {
result = true;
}
return result;
}
#Override
public E next() {
if (current == null) {
try {
current = iterators.remove(0);
} catch (IndexOutOfBoundsException e) {
throw new NoSuchElementException();
}
}
E result = current.next(); // if this method was called without checking 'hasNext' this line might raise NoSuchElementException which is fine
iterators.add(current);
current = iterators.remove(0);
return result;
}
// test
public static void main(String[] args) {
List<Integer> a = new LinkedList<>();
a.add(1);
a.add(7);
a.add(13);
a.add(17);
List<Integer> b = new LinkedList<>();
b.add(2);
b.add(8);
b.add(14);
b.add(18);
List<Integer> c = new LinkedList<>();
c.add(3);
c.add(9);
List<Integer> d = new LinkedList<>();
d.add(4);
d.add(10);
d.add(15);
List<Integer> e = new LinkedList<>();
e.add(5);
e.add(11);
List<Integer> f = new LinkedList<>();
f.add(6);
f.add(12);
f.add(16);
f.add(19);
List<Iterator<Integer>> iterators = new LinkedList<>();
iterators.add(a.iterator());
iterators.add(b.iterator());
iterators.add(c.iterator());
iterators.add(d.iterator());
iterators.add(e.iterator());
iterators.add(f.iterator());
MultiIterator<Integer> it = new MultiIterator<>(iterators.iterator());
while (it.hasNext()) {
System.out.print(it.next() + ","); // prints: 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,
}
}
}
and the second ('greedy' copying of all the elements from all the iterators in the requested order into a list and returning an iterator to that list ):
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
public class MultiIterator<E> {
Iterator<Iterator<E>> iterator = null;
List<E> elements = new LinkedList<>();
private MultiIterator(Iterator<Iterator<E>> iterator) {
this.iterator = iterator;
}
private void copyElementsInOrder() {
List<Iterator<E>> iterators = new LinkedList<>();
// copy the iterators into a list
while (iterator.hasNext()) {
iterators.add(iterator.next());
}
// go over the list, round-robin, and grab one
// element from each sub-iterator and add it to *elements*
// empty sub-iterators will get dropped off the list
while (!iterators.isEmpty()) {
Iterator<E> subIterator = iterators.remove(0);
if (subIterator.hasNext()) {
elements.add(subIterator.next());
iterators.add(subIterator);
}
}
}
public static <E> Iterator<E> iterator(Iterator<Iterator<E>> iterator) {
MultiIterator<E> instance = new MultiIterator<>(iterator);
instance.copyElementsInOrder();
return instance.elements.iterator();
}
// test
public static void main(String[] args) {
List<Integer> a = new LinkedList<>();
a.add(1);
a.add(7);
a.add(13);
a.add(17);
List<Integer> b = new LinkedList<>();
b.add(2);
b.add(8);
b.add(14);
b.add(18);
List<Integer> c = new LinkedList<>();
c.add(3);
c.add(9);
List<Integer> d = new LinkedList<>();
d.add(4);
d.add(10);
d.add(15);
List<Integer> e = new LinkedList<>();
e.add(5);
e.add(11);
List<Integer> f = new LinkedList<>();
f.add(6);
f.add(12);
f.add(16);
f.add(19);
List<Iterator<Integer>> iterators = new LinkedList<>();
iterators.add(a.iterator());
iterators.add(b.iterator());
iterators.add(c.iterator());
iterators.add(d.iterator());
iterators.add(e.iterator());
iterators.add(f.iterator());
Iterator<Integer> it = MultiIterator.<Integer>iterator(iterators.iterator());
while (it.hasNext()) {
System.out.print(it.next() + ","); // prints: 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,
}
}
}
I included a simple 'test' code in order to show the way to use the MultiIterator, this is not always trivial (because of the use of Generics) as you can see on the line:
Iterator<Integer> it = MultiIterator.<Integer>iterator(iterators.iterator());
Here is another implementation:
import java.util.Iterator;
import java.util.NoSuchElementException;
import static java.util.Collections.emptyIterator;
public class Multiterator<E> implements Iterator<E> {
private Iterator<Iterator<E>> root;
private Iterator<E> current;
public Multiterator(Iterator<Iterator<E>> root) {
this.root = root;
current = null;
}
#Override
public boolean hasNext() {
if (current == null || !current.hasNext()) {
current = getNextNonNullOrEmpty(root);
}
return current.hasNext();
}
private Iterator<E> getNextNonNullOrEmpty(Iterator<Iterator<E>> root) {
while (root.hasNext()) {
Iterator<E> next = root.next();
if (next != null && next.hasNext()) {
return next;
}
}
return emptyIterator();
}
#Override
public E next() {
if (current == null) {
throw new NoSuchElementException();
}
return current.next();
}
}
First, take a look at the implementation of the iterator in java.util.LinkedList
http://www.docjar.com/html/api/java/util/LinkedList.java.html
From there your task is easy just implement a single iterator that takes into account the fact that it is iterating over collections.
Regards.
if all you have to work with is the java Iterator: which just have hasNext(), next() and remove(), i figured you have to go around it.
Process it as you will process a 2D array, that is, with an outer and inner loop, because they have same "arrangement" but different datatype. As you process, you transfer them to a new collection.
so maybe a private method:
private void convertToSingleCollection()
{
while("column")
{
//convert the "column" to an arra
for( "Row")
{
//add to newCollection here
}
//remove the processed column from CollectionOFcollection
}
}
//call the above method in your constructor
public iterator<T> Iterator()
{
newCollection.iterator();
}
public boolean hasNext()
{
return Iterator().hasNext()
}
public T next()
{
if(!hasNext())
{
//exception message or message
}
else
//return "next"
}
end
I hope this helps. There should be other ways to solve it i guess.

Categories

Resources