我有两个Flux
对象,例如:
Flux<Item>
和Flux<Transformation>
data class Item(val value: Int)
data class Transformation(val type: String, val value: Int)
我想将所有转换应用于每个项目 - 例如:
var item = Item(15)
val transformations = listOf(Transformation(type = "MULTIPLY", value = 8), ...)
transformations.forEach {
if (it.type == "MULTIPLY") {
item = Item(item.value * it.value)
}
}
但当有Flux
'es的Item
和Transformation
时
您可以使用java.util.function.UnaryOperator
而不是Transformation
类。希望这个Java示例可以帮助您:
@Test
public void test() {
Flux<Item> items = Flux.just(new Item(10), new Item(20));
Flux<UnaryOperator<Item>> transformations = Flux.just(
item -> new Item(item.value * 8),
item -> new Item(item.value - 3));
Flux<Item> transformed = items.flatMap(item -> transformations
.collectList()
.map(unaryOperators -> transformFunction(unaryOperators)
.apply(item)));
System.out.println(transformed.collectList().block());
}
Function<Item, Item> transformFunction(List<UnaryOperator<Item>> itemUnaryOperators) {
Function<Item, Item> transformFunction = UnaryOperator.identity();
for (UnaryOperator<Item> itemUnaryOperator : itemUnaryOperators) {
transformFunction = transformFunction.andThen(itemUnaryOperator);
}
return transformFunction;
}