com.github.javachat.streems.spliterators.BreadthFirstSpliterator Maven / Gradle / Ivy
package com.github.javachat.streems.spliterators;
import java.util.ArrayDeque;
import java.util.Collections;
import java.util.Deque;
import java.util.Iterator;
import java.util.function.Consumer;
import java.util.function.Function;
/**
* A spliterator for breadth-first traversal
*
* @param type of the nodes in the tree
*/
public final class BreadthFirstSpliterator
extends NaryTreeSpliterator
{
private final Deque> deque = new ArrayDeque<>();
public BreadthFirstSpliterator(final T root,
final Function> fn)
{
super(root, fn);
deque.addFirst(Collections.singleton(root).iterator());
}
@SuppressWarnings("TailRecursion")
@Override
public boolean tryAdvance(final Consumer super T> action)
{
Iterator iterator;
T element;
while (!deque.isEmpty()) {
iterator = deque.getFirst();
if (!iterator.hasNext()) {
deque.removeFirst();
continue;
}
element = iterator.next();
deque.add(fn.apply(element));
action.accept(element);
return true;
}
return false;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy