Class CartesianProductIterator<E>
- java.lang.Object
-
- org.apache.commons.collections4.iterators.CartesianProductIterator<E>
-
- Type Parameters:
E- the type of the objects being permuted
- All Implemented Interfaces:
java.util.Iterator<java.util.List<E>>
public class CartesianProductIterator<E> extends java.lang.Object implements java.util.Iterator<java.util.List<E>>
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 anUnsupportedOperationException.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
Constructors Constructor Description CartesianProductIterator(java.lang.Iterable<? extends E>... iterables)Constructs a newCartesianProductIteratorinstance with given iterables.
-
Method Summary
All Methods Instance Methods Concrete Methods Modifier and Type Method Description booleanhasNext()Returnstrueif the iteration has more elements.java.util.List<E>next()Returns the next tuple of the input iterables.voidremove()
-
-
-
Constructor Detail
-
CartesianProductIterator
@SafeVarargs public CartesianProductIterator(java.lang.Iterable<? extends E>... iterables)
Constructs a newCartesianProductIteratorinstance with given iterables.- Parameters:
iterables- the iterables to create the Cartesian product from- Throws:
java.lang.NullPointerException- if any of the iterables is null
-
-
Method Detail
-
hasNext
public boolean hasNext()
Returnstrueif the iteration has more elements.- Specified by:
hasNextin interfacejava.util.Iterator<E>- Returns:
- true if there are more tuples, otherwise false
-
next
public java.util.List<E> next()
Returns the next tuple of the input iterables.- Specified by:
nextin interfacejava.util.Iterator<E>- Returns:
- a list of the input iterables' elements
- Throws:
java.util.NoSuchElementException- if there are no more tuples
-
-