package xdean.jex.extra;

import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import xdean.jex.util.task.TaskUtil;

public class IntSequence implements Iterator<Integer> {
  final Set<Integer> useSet, releaseSet;
  final int min;
  transient int current;

  public IntSequence(int start) {
    this.useSet = new HashSet<>();
    this.releaseSet = new HashSet<>();
    this.min = start;
    this.current = start - 1;
  }

  @Override
  public boolean hasNext() {
    return true;
  }

  @Override
  public synchronized Integer next() {
    if (releaseSet.isEmpty()) {
      while (useSet.remove(++current)) {
        ;
      }
      return current;
    } else {
      return TaskUtil.andFinal(() -> Collections.min(releaseSet), i -> releaseSet.remove(i));
    }
  }

  public synchronized boolean release(int i) {
    if (i >= min && i <= current || useSet.remove(i)) {
      return releaseSet.add(i);
    }
    return false;
  }

  public synchronized boolean use(int i) {
    if (i > current || releaseSet.remove(i)) {
      return useSet.add(i);
    }
    return false;
  }
}

@@ -42,100 +42,63 @@
 til.
-Collections;%0D%0Aimport java.util.HashSet;%0D%0Aimport java.util.Iterator;%0D%0Aimport java.util.Set;%0D%0A
+Iterator;%0D%0A%0D%0Aimport xdean.jex.extra.collection.IntList;
 %0D%0Aim
@@ -204,20 +204,15 @@
 nal 
-Set%3CInteger%3E
+IntList
  use
@@ -324,37 +324,38 @@
 is.useSet = 
-new HashSet%3C%3E
+IntList.create
 ();%0D%0A    thi
@@ -373,21 +373,22 @@
 t = 
-new HashSet%3C%3E
+IntList.create
 ();%0D
@@ -743,34 +743,43 @@
  -%3E 
-Collections.min(releaseSet
+releaseSet.stream().min().getAsInt(
 ), i

use IntList in IntSequence