Class AppendableTraverser<T>

Type Parameters:
T - item type
All Implemented Interfaces:

public class AppendableTraverser<T>
extends Object
implements Traverser<T>
A traverser with an internal ArrayDeque. You can efficiently append(T) items to it that will be later traversed.

It's useful to be returned from a flat-mapping function when an item is flat-mapped to a small number of items:

     Traverser<Integer> at = new AppendableTraverser(2);
     Traverser<Integer> t = Traverser.over(10, 20)
         .flatMap(item -> {
             at.append(item + 1);
             return at;
The t traverser above will output {10, 11, 20, 21}. This approach reduces the GC pressure by avoiding the allocation of a new traverser for each item that will traverse over just a few or even zero items.

See ResettableSingletonTraverser if you have at most one item to traverse.

  • Constructor Details

    • AppendableTraverser

      public AppendableTraverser​(int initialCapacity)
      Creates an appendable traverser.
  • Method Details

    • append

      @Nonnull public AppendableTraverser<T> append​(@Nonnull T item)
      Returns a traverser that will return all the items of this traverser, plus an additional item once this one returns null. After that it continues forwarding the return values of this traverser. It is meant to be used on finite traversers.

      Default implementations always returns a new traverser instance. If you need to append multiple objects or use this method frequently, AppendableTraverser might be a better choice.

      Specified by:
      append in interface Traverser<T>
      this instance
    • next

      public T next()
      Description copied from interface: Traverser
      Returns the next item, removing it from this traverser. If no item is available, returns null. If this traverser is null-terminated, getting a null means it's exhausted and will keep returning null forever. Otherwise, trying again later may produce one.
      Specified by:
      next in interface Traverser<T>
    • isEmpty

      public boolean isEmpty()
      Returns true, if the next call to next() will return null.