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

com.vladsch.flexmark.util.collection.iteration.Reverse Maven / Gradle / Ivy

The newest version!
package com.vladsch.flexmark.util.collection.iteration;

import java.util.List;
import org.jetbrains.annotations.NotNull;

public class Reverse implements ReversibleIterable {
  private final @NotNull List list;
  private final boolean isReversed;

  public Reverse(@NotNull List list) {
    this(list, true);
  }

  public Reverse(@NotNull List list, boolean isReversed) {
    this.list = list;
    this.isReversed = isReversed;
  }

  static class ReversedListIterator implements ReversibleIterator {
    private final @NotNull List list;
    private final boolean isReversed;
    private int index;

    ReversedListIterator(@NotNull List list, boolean isReversed) {
      this.list = list;
      this.isReversed = isReversed;
      if (isReversed) {
        this.index = list.size() == 0 ? -1 : list.size() - 1;
      } else {
        this.index = list.size() == 0 ? -1 : 0;
      }
    }

    @Override
    public boolean isReversed() {
      return isReversed;
    }

    @Override
    public void remove() {}

    @Override
    public boolean hasNext() {
      return index != -1;
    }

    @Override
    public T next() {
      T t = list.get(index);
      if (index != -1) {
        if (isReversed) {
          index--;
        } else {
          if (index == list.size() - 1) {
            index = -1;
          } else {
            index++;
          }
        }
      }

      return t;
    }
  }

  @NotNull
  @Override
  public ReversibleIterator iterator() {
    return new ReversedListIterator<>(list, isReversed);
  }

  @NotNull
  @Override
  public ReversibleIterable reversed() {
    return new Reverse<>(list, !isReversed);
  }

  @Override
  public boolean isReversed() {
    return isReversed;
  }

  @NotNull
  @Override
  public ReversibleIterator reversedIterator() {
    return new ReversedListIterator<>(list, !isReversed);
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy