Class CartesianProductIterator<E>
java.lang.Object
org.apache.commons.collections4.iterators.CartesianProductIterator<E>
- Type Parameters:
E
- the type of the objects being permuted
This iterator creates a Cartesian product of the input iterables,
equivalent to nested for-loops.
The iterables provided to the constructor are used in reverse order, each until exhaustion before proceeding to the next element of the prior iterable and repeating. Consider the following example:
List<Character> iterable1 = Arrays.asList('A', 'B', 'C');
List<Character> iterable2 = Arrays.asList('1', '2', '3');
CartesianProductIterator<Character> it = new CartesianProductIterator<>(
iterable1,
iterable2);
while (it.hasNext()) {
List<Character> tuple = it.next();
System.out.println(tuple.get(0) + ", " + tuple.get(1));
}
The output will be:
A, 1 A, 2 A, 3 B, 1 B, 2 B, 3 C, 1 C, 2 C, 3
The remove()
operation is not supported, and will throw an
UnsupportedOperationException
.
If any of the input iterables is empty, the Cartesian product will be empty. If any of the input iterables is infinite, the Cartesian product will be infinite.
- Since:
- 4.5.0-M3
-
Constructor Summary
ConstructorDescriptionCartesianProductIterator
(Iterable<? extends E>... iterables) Constructs a newCartesianProductIterator
instance with given iterables. -
Method Summary
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
Methods inherited from interface java.util.Iterator
forEachRemaining
-
Constructor Details
-
CartesianProductIterator
Constructs a newCartesianProductIterator
instance with given iterables.- Parameters:
iterables
- the iterables to create the Cartesian product from- Throws:
NullPointerException
- if any of the iterables is null
-
-
Method Details
-
hasNext
Returnstrue
if the iteration has more elements. -
next
Returns the next tuple of the input iterables.- Specified by:
next
in interfaceIterator<E>
- Returns:
- a list of the input iterables' elements
- Throws:
NoSuchElementException
- if there are no more tuples
-
remove
-