khachik khachik - 1 month ago 6
Java Question

Python `itertools.chain` equivalent in Java?

Is there an equivalent of python's

for Java (with third-party libraries or without)?

itertools.chain([1, 2, 3], [4, 5, 6]) # -> [1, 2, 3, 4, 5, 6]


Something like this:

new Iterable<E> {
public Iterator<E> iterator() {
return new Iterator<E>() {
Iterator<E> i1 = list1.iterator();
Iterator<E> i2 = list2.iterator();
public boolean hasNext() {
return i1.hasNext() || i2.hasNext();
}
public E next() {
if(i1.hasNext()) {
return i1.next();
} else if(i2.hasNext()) {
return i2.next();
} else {
throw new NoSuchElementException("Lists exhausted");
}
}
public void remove() {
throw new UnsupportedOperationException("...");
}
}
}
}

Answer