springboot webflux flux 使用示例(聚合操作)
*************************
group
public class Test {
public static void main(String[] args){
Flux.just(1,2,3,4,5,6).groupBy(value -> value<3)
.subscribe(flux -> {
if (Objects.equals(flux.key(),Boolean.TRUE)){
System.out.print("key爲"+flux.key()+"的個數爲:");
flux.count().subscribe(System.out::println);
}
});
}
}
********************
控制檯輸出
key爲true的個數爲:2
*************************
sort、distinct、count
public class Test2 {
public static void main(String[] args){
Flux.just(1,20,31,4,5,6,65,23,12,32).sort()
.subscribe(value ->System.out.print(value+" "));
System.out.println("\n\n***************");
Flux.just("瓜田李下","瓜田李下2","hello world","hello world","gtlx","瓜田李下")
.distinct()
.subscribe(value -> System.out.print(value+" "));
System.out.println("\n\n***************");
Flux.just("瓜田李下","瓜田李下2","hello world","hello world2")
.count()
.subscribe(value -> System.out.println("元素的個數爲:"+value));
}
}
********************
控制檯輸出
1 4 5 6 12 20 23 31 32 65
***************
瓜田李下 瓜田李下2 hello world gtlx
***************
元素的個數爲:4
*************************
reduce
public class Test3 {
public static void main(String[] args){
Flux.just(1,2,3,4).reduce(Integer::sum).subscribe(System.out::println);
Flux.just(1,2,3,4).reduce(10,Integer::sum).subscribe(System.out::println);
}
}
********************
控制檯輸出
10
20