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

org.libj.util.FlatIterableIterator Maven / Gradle / Ivy

Go to download

Supplementary utilities for classes that belong to java.util, or are considered essential as to justify existence in java.util.

There is a newer version: 0.9.1
Show newest version
/* Copyright (c) 2019 LibJ
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * You should have received a copy of The MIT License (MIT) along with this
 * program. If not, see .
 */

package org.libj.util;

import java.util.Iterator;
import java.util.NoSuchElementException;

/**
 * An {@link Iterator} for N-dimensional collections implementing the
 * {@link Iterable} interface of type {@code } that iterates through the leaf
 * members of the collections of type {@code }.
 *
 * @param  The type of leaf member elements.
 * @param  The type of the collection.
 */
public abstract class FlatIterableIterator extends FlatIterator> {
  private E next;

  /**
   * Creates a new {@link FlatSequentialIterator} for collection to be iterated.
   *
   * @param c The collection to be iterated.
   * @throws NullPointerException If the specified collection is null.
   */
  public FlatIterableIterator(final T c) {
    stack.add(iterator(c));
  }

  /**
   * Returns an {@link Iterator} for the specified collection.
   *
   * @param c The collection.
   * @return An {@link Iterator} for the specified collection.
   * @throws NullPointerException If the specified collection is null.
   */
  protected abstract Iterator iterator(T c);

  @Override
  @SuppressWarnings("unchecked")
  public boolean hasNext() {
    if (hasNext)
      return true;

    for (Iterator current;;) {
      while (!(current = stack.get(stack.size() - 1)).hasNext()) {
        stack.remove(stack.size() - 1);
        if (stack.size() == 0)
          return false;
      }

      final Object next = current.next();
      if (next == null || !isIterable(next)) {
        this.next = (E)next;
        return hasNext = true;
      }

      stack.add(iterator((T)next));
    }
  }

  @Override
  public E next() {
    if (!hasNext && !hasNext())
      throw new NoSuchElementException();

    hasNext = false;
    return next;
  }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy