net.sf.staccatocommons.collections.stream.internal.algorithms.SingleLinkedDelayedQueue Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of commons-collections Show documentation
Show all versions of commons-collections Show documentation
Collections library of the Staccato-Commons project, focused on providing new abstractions
that mix object oriented and functional programming style for dealing with iterable objects.
The newest version!
/*
Copyright (c) 2011, The Staccato-Commons Team
This program 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; version 3 of the License.
This program 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.
*/
package net.sf.staccatocommons.collections.stream.internal.algorithms;
import java.util.NoSuchElementException;
import net.sf.staccatocommons.defs.Thunk;
import net.sf.staccatocommons.defs.partial.EmptyAware;
import net.sf.staccatocommons.iterators.thriter.AdvanceThriterator;
import net.sf.staccatocommons.iterators.thriter.Thriterator;
import net.sf.staccatocommons.lang.thunk.Thunks;
import net.sf.staccatocommons.restrictions.check.NonNull;
import net.sf.staccatocommons.restrictions.processing.EnforceRestrictions;
import org.apache.commons.lang.StringUtils;
/**
* A basic implementation of a single FIFO linked list, with lazy elements
*
* @author flbulgarelli
*
*/
public class SingleLinkedDelayedQueue implements Iterable, EmptyAware {
private final Cell head = new Cell(Thunks. undefined());
private Cell last = head;
/**
* Adds an element at the end of the queue
*
* @param element
*/
@EnforceRestrictions
public void add(@NonNull Thunk element) {
Cell prev = last;
last = new Cell(element);
prev.next = last;
}
@Override
public Thriterator iterator() {
return new Iter(head);
}
private static final class Cell {
private final Thunk element;
private Cell next;
public Cell(Thunk element) {
this.element = element;
}
boolean hasNext() {
return next != null;
}
}
@Override
public boolean isEmpty() {
return !head.hasNext();
}
@Override
public String toString() {
return "[" + StringUtils.join(iterator(), ",") + "]";
}
private static final class Iter extends AdvanceThriterator {
private Cell current;
public Iter(Cell current) {
this.current = current;
}
public boolean hasNext() {
return current.hasNext();
}
public void advanceNext() throws NoSuchElementException {
current = current.next;
}
public A current() {
return delayedCurrent().value();
}
@Override
public Thunk delayedCurrent() {
return current.element;
}
}
}