Java将列表缩减为回退链
假设我有一个Java中一些实体的列表,比如
List<Entity> entities = Arrays.asList(entity1, entity2, entity3...);
我想将其简化为一个链对象的实例,如:
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);
}
}
}
EntityChain
是不可变的,并且有一个生成器
因此,结果将是一个EntityChain
实例,如:
chain
-> entity = entity1
-> fallback
-> entity = entity2
-> fallback
-> entity = entity3
-> fallback
...
有没有可能通过一些神奇的Java8Fluent简化来实现这一点
是
Stream.reduce(U identity,
BiFunction<U, ? super T, U> accumulator,
BinaryOperator<U> combiner)
适用于这里吗?以某种方式使用它的生成器
# 1 楼答案
经过思考,我发现在顺序流中减少时,我可以完全移除holder
Supplier<EntityChain>
。该算法是逆向构建实体链:首先构建实体(n),然后构建实体(n-1)。。。实体(0)输出
# 2 楼答案
为了将列表简化为生成器,需要一个累加器(
Builder::withEntity
)和一个组合器(Builder::combine
):这张照片是:
# 3 楼答案
您可以在需要时懒散地构建
EntityChain
。我用Supplier<EntityChain>
完成它输出