Suppose I have a list of some objects in Java, for example
List<Entity> entities = Arrays.asList(entity1, entity2, entity3...);
I would like to reduce it to one instance of a chain object, for example:
class EntityChain {
private final Entity entity;
private final Optional<EntityChain> fallback;
private EntityChain(Builder builder) {
this.entity = builder.entity;
this.fallback = builder.fallback;
}
public static Builder builder() {
return new Builder();
}
public static final class Builder {
private Entity entity;
private Optional<EntityChain> fallback = Optional.empty();
public Builder withEntity(Entity entity) {
this.entity = entity;
return this;
}
public Builder withFallback(EntityChain fallback) {
this.fallback = Optional.of(fallback);
return this;
}
public EntityChain build() {
return new EntityChain(this);
}
}
}
EntityChainis immutable and has a builder.
Thus, the result will be an instance EntityChain, for example:
chain
-> entity = entity1
-> fallback
-> entity = entity2
-> fallback
-> entity = entity3
-> fallback
...
Is it possible to do this with some magic version of Java 8? Is an
Stream.reduce(U identity,
BiFunction<U, ? super T, U> accumulator,
BinaryOperator<U> combiner)
applicable here? Somehow this is a builder?
source
share