说我有两个Flux如下:
Flux<Integer> f1 = Flux.just(10,20,30,40);
Flux<Integer> f2 = Flux.just(100,200,300,400);
现在我想要的是将这些通量组合成一个Flux或两个Flux的元组,它将在一个Flux中具有两个Flux的元素。
我使用zipwith方法尝试了以下方法:
Flux<Integer, Integer> zipped = f1.zipWith(f2,
(one, two) -> one + "," +two)
.subscribe();
但这会产生编译时错误:
Incorrect number of arguments for type Flux<T>; it cannot be parameterized with arguments <Integer, Integer>
我怎样才能做到这一点? 请建议。
答案 0 :(得分:2)
Flux只有一个类型的参数,所以Flux<Integer,Integer>
是不可能的,我不确定你用one + "," + two
试图实现什么,但是这个表达式的类型是String。
因此,实质上,您将两个整数映射到String,因此zipped
的类型应为Flux<String>
。
或者,您可以映射到您自己制作的特殊元组类(或者可能来自您正在使用的库):
public class Pair<A,B> {
private final A first;
private final B second;
public Pair(A first, B second) {
this.first = first;
this.second = second;
}
public A getFirst() {
return first;
}
public B getSecond() {
return second;
}
}
然后您可以按如下方式映射:
Flux<Integer> f1 = Flux.just(10,20,30,40);
Flux<Integer> f2 = Flux.just(100,200,300,400);
Flux<Pair<Integer,Integer>> result = f1.zipWith(f2,
(one, two) -> new Pair<>(one, two));
甚至更短:
Flux<Pair<Integer,Integer>> result = f1.zipWith(f2, Pair::new);