当前位置: 移动技术网 > IT编程>开发语言>.net > Reactor 3 (13): 数据收集 collect

Reactor 3 (13): 数据收集 collect

2020年08月10日  | 移动技术网IT编程  | 我要评论
有的时候流数据有需要转化为其他类型数据,同Stream相同,Reactor也有将数据进行收集的方法:collect () : 将数据根据给出的collector进行收集collectList() : 收集收集为list形式collectSortedList(): 数据收集为list并排序,需要给出排序规则collectMap(): 数据收集为Map形式,是key,value形式,因此如果有重复key会覆盖collectMultimap(): 数据收集为Map形式,是key,collection

有的时候流数据有需要转化为其他类型数据,同Stream相同,Reactor也有将数据进行收集的方法:

  • collect () : 将数据根据给出的collector进行收集
  • collectList() : 收集收集为list形式
  • collectSortedList(): 数据收集为list并排序,需要给出排序规则
  • collectMap(): 数据收集为Map形式,是key,value形式,因此如果有重复key会覆盖
  • collectMultimap(): 数据收集为Map形式,是key,collection形式,如果有重复key值写在list中

collect()方法

图示:

在这里插入图片描述

代码示例:

  • 需要注意的是收集后的为Mono
    @Test
    public void collectTest() {
        Mono<Set<String>> flux = Flux.just("ffzs", "vincent", "tony", "sleepycate")
                .collect(Collectors.toSet())
                .log();

        flux.subscribe();
    }

collectList() 方法

图示:

在这里插入图片描述

代码示例:

  • 直接收集为Mono<List<>>
@Test
public void collectListTest() {
    Flux.just("ffzs", "vincent", "tony", "sleepycate")
            .collectList()
            .log()
            .subscribe();
}

在这里插入图片描述

collectSortedList()方法

代码示例:

@Test
public void collectSortedListTest() {
    Flux.just("ffzs", "vincent", "tony", "sleepycate")
            .collectSortedList(Comparator.comparing(String::length))
            .log()
            .subscribe();
}

在这里插入图片描述

结果为排过顺序的。

collectMap()方法

在这里插入图片描述

代码示例:

  • 根据字符串的长度作为key
@Test
public void collectMapTest() {
    Flux.just("ffzs", "vincent", "tony", "sleepycate")
            .collectMap(String::length)
            .log()
            .subscribe();
}

在这里插入图片描述

由于 ffzs和tony长度都是4,因此ffzs被tony覆盖掉了

collectMultimap()方法

在这里插入图片描述

代码示例:

@Test
public void collectMultimapTest() {
    Flux.just("ffzs", "vincent", "tony", "sleepycate")
            .collectMultimap(String::length)
            .log()
            .subscribe();
}

在这里插入图片描述

所有数据都收集到collection中

代码

github
gitee

本文地址:https://blog.csdn.net/tonydz0523/article/details/107892515

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网