package org.eclipse.collections.impl.lazy;
import java.util.Iterator;
import org.eclipse.collections.api.block.procedure.Procedure;
import org.eclipse.collections.api.block.procedure.Procedure2;
import org.eclipse.collections.api.block.procedure.primitive.ObjectIntProcedure;
import org.eclipse.collections.impl.lazy.iterator.TakeIterator;
public class TakeIterable<T> extends AbstractLazyIterable<T>
{
private final Iterable<T> adapted;
private final int count;
public TakeIterable(Iterable<T> newAdapted, int count)
{
if (count < 0)
{
throw new IllegalArgumentException("Count must be greater than zero, but was: " + count);
}
this.adapted = newAdapted;
this.count = count;
}
@Override
public void each(Procedure<? super T> procedure)
{
int i = 0;
Iterator<T> iterator = this.adapted.iterator();
while (i < this.count && iterator.hasNext())
{
procedure.value(iterator.next());
i++;
}
}
@Override
public void forEachWithIndex(ObjectIntProcedure<? super T> procedure)
{
int i = 0;
Iterator<T> iterator = this.adapted.iterator();
while (i < this.count && iterator.hasNext())
{
procedure.value(iterator.next(), i);
i++;
}
}
@Override
public <P> void forEachWith(Procedure2<? super T, ? super P> procedure, P parameter)
{
int i = 0;
Iterator<T> iterator = this.adapted.iterator();
while (i < this.count && iterator.hasNext())
{
procedure.value(iterator.next(), parameter);
i++;
}
}
@Override
public Object[] toArray()
{
Object[] result = new Object[this.count];
this.forEachWithIndex((each, index) -> result[index] = each);
return result;
}
@Override
public Iterator<T> iterator()
{
return new TakeIterator<>(this.adapted, this.count);
}
}