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

org.infinispan.commons.util.RemovableIterator Maven / Gradle / Ivy

There is a newer version: 15.1.0.Dev03
Show newest version
package org.infinispan.commons.util;

import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.function.Consumer;

/**
 * An Iterator implementation that allows for a Iterator that doesn't allow remove operations to
 * implement remove by delegating the call to the provided consumer to remove the previously read value.
 *
 * @author wburns
 * @since 9.1
 */
public class RemovableIterator implements Iterator {
   protected final Iterator realIterator;
   protected final Consumer consumer;

   protected C previousValue;
   protected C currentValue;

   public RemovableIterator(Iterator realIterator, Consumer consumer) {
      this.realIterator = realIterator;
      this.consumer = consumer;
   }

   protected C getNextFromIterator() {
      if (realIterator.hasNext()) {
         return realIterator.next();
      } else {
         return null;
      }
   }

   @Override
   public boolean hasNext() {
      return currentValue != null || (currentValue = getNextFromIterator()) != null;
   }

   @Override
   public C next() {
      if (!hasNext()) {
         throw new NoSuchElementException();
      }
      previousValue = currentValue;
      currentValue = null;
      return previousValue;
   }

   @Override
   public void remove() {
      if (previousValue == null) {
         throw new IllegalStateException();
      }
      consumer.accept(previousValue);
      previousValue = null;
   }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy