cn.allbs.hj212.core.MapEntryStepGenerator Maven / Gradle / Ivy
package cn.allbs.hj212.core;
import java.util.function.BiConsumer;
import java.util.function.BinaryOperator;
import java.util.function.Supplier;
/**
* 功能:
*
* @author chenQi
*/
public class MapEntryStepGenerator {
private BiConsumer consumer;
private BinaryOperator keyMergeOperator;
private BinaryOperator valueMergeOperator;
private Token token;
private K k;
private V v;
private Supplier kSupplier;
private Supplier vSupplier;
private MapEntryStepGenerator(BiConsumer consumer, BinaryOperator keyMergeOperator, BinaryOperator valueMergeOperator) {
this.consumer = consumer;
this.keyMergeOperator = keyMergeOperator;
this.valueMergeOperator = valueMergeOperator;
this.token = Token.NONE;
}
public void putKey(K k) {
switch (token) {
case KEY:
this.k = keyMergeOperator.apply(this.k, k);
break;
case VALUE:
generate();
case NONE:
this.k = k;
this.token = Token.KEY;
break;
}
}
public void putValue(V v) {
switch (token) {
case VALUE:
this.v = valueMergeOperator.apply(this.v, v);
break;
case NONE:
case KEY:
this.v = v;
this.token = Token.VALUE;
break;
}
}
public void generate() {
this.consumer.accept(this.k, this.v);
this.k = kSupplier == null ? null : kSupplier.get();
this.v = vSupplier == null ? null : vSupplier.get();
}
enum Token {
NONE,
KEY,
VALUE
}
public static Builder builder() {
return new Builder();
}
public static class Builder {
MapEntryStepGenerator result = new MapEntryStepGenerator<>(null, null, null);
public Builder consumer(BiConsumer consumer) {
result.consumer = consumer;
return this;
}
public Builder keyMergeOperator(BinaryOperator keyMergeOperator) {
result.keyMergeOperator = keyMergeOperator;
return this;
}
public Builder valueMergeOperator(BinaryOperator valueMergeOperator) {
result.valueMergeOperator = valueMergeOperator;
return this;
}
public Builder keyDefault(Supplier keySupplier) {
result.kSupplier = keySupplier;
return this;
}
public Builder valueDefault(Supplier valueSupplier) {
result.vSupplier = valueSupplier;
return this;
}
public MapEntryStepGenerator create() {
if (result.consumer == null) {
throw new IllegalArgumentException("consumer");
}
if (result.keyMergeOperator == null) {
throw new IllegalArgumentException("keyMergeOperator");
}
if (result.valueMergeOperator == null) {
throw new IllegalArgumentException("valueMergeOperator");
}
return result;
}
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy