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

me.shaftesbury.utils.functional.Iterators Maven / Gradle / Ivy

There is a newer version: 1.17
Show newest version
package me.shaftesbury.utils.functional;

import java.util.Iterator;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: Bob
 * Date: 23/10/13
 * Time: 11:39
 * To change this template use File | Settings | File Templates.
 */
public final class Iterators
{
    private Iterators(){}

    public static final Iterable reverse(final List list)
    {
        if (list == null) throw new IllegalArgumentException("list");

        if (list.isEmpty())
            throw new IllegalArgumentException("Collection is empty");

        return new Iterable() {
            private final List _list=list;
            @Override
            public Iterator iterator() {
                return new Iterator() {
                    private int _posn=list.size()-1;
                    @Override
                    public boolean hasNext() {
                        return _posn>=0;
                    }

                    @Override
                    public T next() {
                        return _list.get(_posn--);
                    }

                    @Override
                    public void remove() {
                        throw new UnsupportedOperationException();
                    }
                };
            }
        };
    }

    // Return the first item of the sequence and then every nth item thereafter
    public static final Iterable everyNth(final int step, final Iterable it)
    {
        if (it == null) throw new IllegalArgumentException("enumerable");

        if (step < 1)
            throw new IllegalArgumentException("Invalid step value, must be greater than zero.");

        return new Iterable(){
            final private Iterable cache = it;

            @Override
            public Iterator iterator() {
                return new Iterator(){
                    private boolean isFirst = true;
                    private boolean isNextReady = true;
                    final private Iterator posn = cache.iterator();

                    @Override
                    public boolean hasNext() {
                        if(isFirst||isNextReady) ;
                        else {
                            for(int i=0;i




© 2015 - 2024 Weber Informatics LLC | Privacy Policy