org.irlab.cartesianproduct.ProductIterator Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of cartesian-product Show documentation
Show all versions of cartesian-product Show documentation
Iterable of the cartesian product of Iterables
The newest version!
/*
* Copyright 2019 Information Retrieval Lab - University of A Coruña
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.irlab.cartesianproduct;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* Cartesian product of two iterables.
*
* Makes the cartesian product of two iterables of type E1 and E2, defining an
* operation to join elements of both types together, that subclasses have to
* define.
*
* @param the type of the elements of the first {@link Iterable}
* @param the type of the elements of the second {@link Iterable}
* @param the type for the result of joining both elements
*
* @author [email protected]
*/
abstract class ProductIterator implements Iterator {
/** Iterator of the first iterable. */
private final Iterator it1;
/** The second iterable. */
private final Iterable col2;
/** Iterator of the second iterable. */
private Iterator it2;
/** The current element in the iteration of the first iterable */
private E1 curr1;
/**
* Instantiates a new product iterator.
*
* @param col1 the first iterable
* @param col2 the second iterable
*/
ProductIterator(final Iterable col1, final Iterable col2) {
this.it1 = col1.iterator();
this.col2 = col2;
this.it2 = col2.iterator();
if (it1.hasNext() && it2.hasNext()) {
curr1 = it1.next();
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean hasNext() {
return (curr1 != null) && (it1.hasNext() || it2.hasNext());
}
/**
* Joins two elements from each iterable into an object of the final type..
*
* @param e1 the element of the first iterable
* @param e2 the element of the second iterable
* @return the resulting object
*/
protected abstract T join(E1 e1, E2 e2);
/**
* {@inheritDoc}
*/
@Override
public T next() {
if (curr1 == null) {
throw new NoSuchElementException();
}
if (it2.hasNext()) {
return join(curr1, it2.next());
} else if (it1.hasNext()) {
curr1 = it1.next();
it2 = col2.iterator();
return join(curr1, it2.next());
} else {
curr1 = null;
throw new NoSuchElementException();
}
}
}