I\'ve created a method that should interweave two list objects and return the new, inter-weaved, list.
i.e. If aList is [A,C,E,G] & bList is [B, D, F] the metho
It is possible to compose the lists dynamically:
static class InterWeave implements Iterable {
// The lists to be interwoven.
final Iterable[] lists;
public InterWeave(Iterable... lists) {
this.lists = lists;
}
@Override
public Iterator iterator() {
return new WeaveIterator();
}
private class WeaveIterator implements Iterator {
// Which list to offer next.
int whichList = 0;
// The Iterators of those lists.
final List> iterators = new ArrayList(lists.length);
// The current iterator.
Iterator i;
// The next to deliver - null menas not primed yet.
T next = null;
public WeaveIterator() {
// Take some iterators.
for (Iterable l : lists) {
if (l != null) {
iterators.add(l.iterator());
}
}
}
@Override
public boolean hasNext() {
// Have we already prepared one?
if (next == null) {
// Grab the next iterator and step on.
i = iterators.get(whichList++);
// detect that we're back at start.
Iterator start = i;
// Cycle around the iterators.
whichList %= iterators.size();
while (!i.hasNext()) {
// Get next one.
i = iterators.get(whichList++);
whichList %= iterators.size();
if (i == start) {
// Stop here if we've gone all the way around.
break;
}
}
if (i.hasNext()) {
next = i.next();
}
}
return next != null;
}
@Override
public T next() {
if (hasNext()) {
T n = next;
// Mark it used.
next = null;
return n;
} else {
throw new NoSuchElementException();
}
}
}
}
public void test() {
List a = Arrays.asList(new String[]{"A", "C", "E", "G"});
List b = Arrays.asList(new String[]{"B", "D", "F"});
for (String s : new InterWeave(a, b)) {
System.out.println(s);
}
}