// Collection of code snippets by Arne Vajhøj 
// (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.function.Supplier;
import java.util.stream.Gatherer;

// WindowCounted<T>:
//   receive one T at a time
//   use an ArrayList,T> as state
//   pass one List<T> at a time to next level
// where number of elements are in the stream itself
public class WindowCounted<T extends Number> implements Gatherer <T, ArrayList<T>, List<T>> {
	private Optional<Integer> n = Optional.empty();
	@Override
	public Supplier<ArrayList<T>> initializer() {
		return () -> new ArrayList<T>();
	}
	@Override
	public Integrator<ArrayList<T>, T, List<T>> integrator() {
		return Gatherer.Integrator.ofGreedy((win, elm, targstm) -> {
			if(n.isEmpty()) {
				n = Optional.of(elm.intValue());
				return true;
			} else {
				win.add(elm);
				if(win.size() == n.get()) {
					List<T> temp = new ArrayList<T>(win);
					win.clear();
					n = Optional.empty();
					return targstm.push(temp);
				} else {
					return true;
				}
			}
		});
	}
}
