All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.codefilarete.tool.collection.ReadOnlyIterator Maven / Gradle / Ivy

package org.codefilarete.tool.collection;

import java.util.Iterator;
import java.util.function.Consumer;

/**
 * A marking class for {@link Iterator} which elements cannot be removed.
 * 
 * @author Guillaume Mary
 */
public abstract class ReadOnlyIterator implements Iterator {
	
	/**
	 * Simple shortcut to {@link ReadOnlyWrappedIterator#ReadOnlyWrappedIterator(Iterator)}, made because it seems more readable
	 * at usage than instantiating the class. Totally subjective.
	 *
	 * @param iterable the {@link Iterable} that the iterator will be taken on
	 * @param  iterator element type
	 * @return a new {@link ReadOnlyIterator} wrapping given {@link Iterable} iterator
	 */
	public static  ReadOnlyIterator wrap(Iterable iterable) {
		return new ReadOnlyWrappedIterator<>(iterable.iterator());
	}
	
	/**
	 * Simple shortcut to {@link ReadOnlyWrappedIterator#ReadOnlyWrappedIterator(Iterator)}, made because it seems more readable
	 * at usage than instantiating the class. Totally subjective.
	 *
	 * @param iterator the wrapped iterator
	 * @param  iterator element type
	 * @return a new {@link ReadOnlyIterator} wrapping given {@link Iterator}
	 */
	public static  ReadOnlyIterator wrap(Iterator iterator) {
		return new ReadOnlyWrappedIterator<>(iterator);
	}
	
	/** Overridden to mark it final */
	@Override
	public final void remove() {
		throw new UnsupportedOperationException();
	}
	
	private static class ReadOnlyWrappedIterator extends ReadOnlyIterator {
		
		private final Iterator surrogate;
		
		public ReadOnlyWrappedIterator(Iterator surrogate) {
			this.surrogate = surrogate;
		}
		
		@Override
		public boolean hasNext() {
			return surrogate.hasNext();
		}
		
		@Override
		public C next() {
			return surrogate.next();
		}
		
		@Override
		public void forEachRemaining(Consumer action) {
			surrogate.forEachRemaining(action);
		}
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy