假设我有一个 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
...
是否可以通过一些神奇的 Java 8 流利减少来做到这一点?
是
Stream.reduce(U identity,
BiFunction<U, ? super T, U> accumulator,
BinaryOperator<U> combiner)
这里适用吗?以某种方式使用它的生成器?
最佳答案
经过思考,我发现我可以把支架拿掉Supplier<EntityChain>
在顺序流中减少时完全。该算法是构建实体链的逆向:首先构建 entity(n) ,然后是 entity(n-1),... entity(0)。
BiFunction<EntityChain, Entity, EntityChain> reducing =
(next, entity) -> Optional.ofNullable(next)
// create a builder with fallback if EntityChain present
.map(fallback -> EntityChain.builder().withFallback(fallback))
// create a builder without fallback
.orElseGet(EntityChain::builder)
//build the EntityChain
.withEntity(entity).build();
// combiner never be used in sequentially stream
BinaryOperator<EntityChain> rejectedInParallelStream = (t1, t2) -> {
//when you use parallel the chain order maybe changed, and the result is wrong.
throw new IllegalStateException("Can't be used in parallel stream!");
};
EntityChain chain = reverse(entities).
stream().reduce(null, reducing, rejectedInParallelStream);
//copy & reverse the copied List
static <T> List<T> reverse(List<T> list) {
List<T> it = list.stream().collect(Collectors.toList());
Collections.reverse(it);
return it;
}
输出
-> entity = entity1
-> fallback
-> entity = entity2
-> fallback (empty)
关于Java减少列表到回退链,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43657061/