summaryrefslogtreecommitdiff
path: root/BJC-Utils2/src/main/java/bjc/utils/funcutils/GroupPartIteration.java
blob: fc58b6a8c18a7fa442a7c5a7c22008417f3bb4e8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package bjc.utils.funcutils;

import java.util.function.Consumer;
import java.util.function.Function;

import bjc.utils.funcdata.FunctionalList;
import bjc.utils.funcdata.IList;

/**
 * Implements a single group partitioning pass on a list
 * 
 * @author ben
 *
 * @param <E>
 *            The type of element in the list being partitioned
 */
final class GroupPartIteration<E> implements Consumer<E> {
	private IList<IList<E>>			returnedList;

	public IList<E>		currentPartition;
	private IList<E>				rejectedItems;

	private int						numberInCurrentPartition;
	private int						numberPerPartition;

	private Function<E, Integer>	elementCounter;

	public GroupPartIteration(IList<IList<E>> returned, IList<E> rejects,
			int nPerPart, Function<E, Integer> eleCount) {
		this.returnedList = returned;
		this.rejectedItems = rejects;
		this.numberPerPartition = nPerPart;
		this.elementCounter = eleCount;

		this.currentPartition = new FunctionalList<>();
		this.numberInCurrentPartition = 0;
	}

	@Override
	public void accept(E value) {
		boolean shouldStartPartition = numberInCurrentPartition >= numberPerPartition;

		if (shouldStartPartition) {
			returnedList.add(currentPartition);

			currentPartition = new FunctionalList<>();
			numberInCurrentPartition = 0;
		} else {
			int currentElementCount = elementCounter.apply(value);

			boolean shouldReject = (numberInCurrentPartition + currentElementCount) >= numberPerPartition;
			
			if (shouldReject) {
				rejectedItems.add(value);
			} else {
				currentPartition.add(value);
				numberInCurrentPartition += currentElementCount;
			}
		}
	}
}