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

org.eclipse.collections.impl.lazy.TakeIterable Maven / Gradle / Ivy

There is a newer version: 12.0.0.M3
Show newest version
/*
 * Copyright (c) 2016 Goldman Sachs.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * and Eclipse Distribution License v. 1.0 which accompany this distribution.
 * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
 * and the Eclipse Distribution License is available at
 * http://www.eclipse.org/org/documents/edl-v10.php.
 */

package org.eclipse.collections.impl.lazy;

import java.util.Iterator;

import net.jcip.annotations.Immutable;
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;

/**
 * Iterates over the first count elements of the adapted Iterable or the full size of the adapted
 * iterable if the count is greater than the length of the receiver.
 */
@Immutable
public class TakeIterable extends AbstractLazyIterable
{
    private final Iterable adapted;
    private final int count;

    public TakeIterable(Iterable newAdapted, int count)
    {
        if (count < 0)
        {
            throw new IllegalArgumentException("Count must be greater than zero, but was: " + count);
        }
        this.adapted = newAdapted;
        this.count = count;
    }

    // TODO: implement in terms of LazyIterate.whileDo() when it is added.

    @Override
    public void each(Procedure procedure)
    {
        int i = 0;
        Iterator iterator = this.adapted.iterator();
        while (i < this.count && iterator.hasNext())
        {
            procedure.value(iterator.next());
            i++;
        }
    }

    @Override
    public void forEachWithIndex(ObjectIntProcedure procedure)
    {
        int i = 0;
        Iterator iterator = this.adapted.iterator();
        while (i < this.count && iterator.hasNext())
        {
            procedure.value(iterator.next(), i);
            i++;
        }
    }

    @Override
    public 

void forEachWith(Procedure2 procedure, P parameter) { int i = 0; Iterator 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 iterator() { return new TakeIterator<>(this.adapted, this.count); } }





© 2015 - 2025 Weber Informatics LLC | Privacy Policy