/*
* GRAL: GRAphing Library for Java(R)
*
* (C) Copyright 2009-2016 Erich Seifert ,
* Michael Seifert
*
* This file is part of GRAL.
*
* GRAL is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GRAL is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with GRAL. If not, see .
*/
package de.erichseifert.gral.util;
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
public abstract class Iterables {
private static class ConcatenationIterable implements Iterable {
private final Iterable> inputIterables;
public ConcatenationIterable(Iterable> inputIterables) {
this.inputIterables = inputIterables;
}
@Override
public Iterator iterator() {
List> iterators = new LinkedList>();
for (Iterable iterable : inputIterables) {
iterators.add(iterable.iterator());
}
@SuppressWarnings("unchecked")
Iterator iterator = new ConcatenationIterator(iterators.toArray(new Iterator[0]));
return iterator;
}
}
public static Iterable concatenate(Iterable... iterables) {
return new ConcatenationIterable(Arrays.asList(iterables));
}
private static class LengthIterator implements Iterator {
private final Iterator inputIterator;
private final int maxElementCount;
private int retrievedElementCount;
public LengthIterator(Iterator inputIterator, int elementCount) {
this.inputIterator = inputIterator;
this.maxElementCount = elementCount;
}
@Override
public boolean hasNext() {
return retrievedElementCount < maxElementCount && inputIterator.hasNext();
}
@Override
public T next() {
retrievedElementCount++;
return inputIterator.next();
}
@Override
public void remove() {
inputIterator.remove();
}
}
public static Iterable take(final Iterable iterable, final int elementCount) {
return new Iterable() {
@Override
public Iterator iterator() {
return new LengthIterator(iterable.iterator(), elementCount);
}
};
}
}
Ads help maintain this website.