Reactor系列(九)collect集合

in 编程
关注公众号【好便宜】( ID:haopianyi222 ),领红包啦~
阿里云,国内最大的云服务商,注册就送数千元优惠券:https://t.cn/AiQe5A0g
腾讯云,良心云,价格优惠: https://t.cn/AieHwwKl
搬瓦工,CN2 GIA 优质线路,搭梯子、海外建站推荐: https://t.cn/AieHwfX9

#java#reactor#collect#collectMap#collectList#

集合

视频讲解: https://www.bilibili.com/video/av79860614/

FluxMonoTestCase.java
package com.example.reactor;

import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.Comparator;
import java.util.List;
import java.util.Map;

@Slf4j
public class FluxMonoTestCase extends BaseTestCase {
    @Test
    public void collect(){
        Flux<Integer> integerFlux = Flux.range(1,5);
        //转换成以List<Integer>为对象的Mono
        Mono<List<Integer>> mono = integerFlux.collectList();
        mono.subscribe(System.out::println);
        Flux<Employee> employeeFlux = Flux.fromIterable(list);
        //转换成以List<Employee>为对象的Mono
        Mono<List<Employee>> mono1 = employeeFlux.collectSortedList(Comparator.comparing(Employee::getSalary));
        mono1.subscribe(System.out::println);
        //转换成以Map<String,Employee>为对象的Mono
        Mono<Map<String,Employee>> mono2 = employeeFlux.collectMap(item ->item.getName(), item ->item);
        mono2.subscribe(System.out::println);
    }
}
BaseTestCase.java
package com.example.reactor;

import java.util.Arrays;
import java.util.List;

public class BaseTestCase {
    protected static final List<Employee> list = Arrays.asList(
            new Employee(1, "Alex", 1000),
            new Employee(2, "Michael", 2000),
            new Employee(3, "Jack", 1500),
            new Employee(4, "Owen", 1500),
            new Employee(5, "Denny", 2000));
}

结果:

[1, 2, 3, 4, 5]
[Employee(id=1, name=Alex, salary=1000.0), Employee(id=3, name=Jack, salary=1500.0), Employee(id=4, name=Owen, salary=1500.0), Employee(id=2, name=Michael, salary=2000.0), Employee(id=5, name=Denny, salary=2000.0)]
{Alex=Employee(id=1, name=Alex, salary=1000.0), Owen=Employee(id=4, name=Owen, salary=1500.0), Denny=Employee(id=5, name=Denny, salary=2000.0), Michael=Employee(id=2, name=Michael, salary=2000.0), Jack=Employee(id=3, name=Jack, salary=1500.0)}

关注公众号,坚持每天3分钟视频学习

关注公众号【好便宜】( ID:haopianyi222 ),领红包啦~
阿里云,国内最大的云服务商,注册就送数千元优惠券:https://t.cn/AiQe5A0g
腾讯云,良心云,价格优惠: https://t.cn/AieHwwKl
搬瓦工,CN2 GIA 优质线路,搭梯子、海外建站推荐: https://t.cn/AieHwfX9
扫一扫关注公众号添加购物返利助手,领红包
Comments are closed.

推荐使用阿里云服务器

超多优惠券

服务器最低一折,一年不到100!

朕已阅去看看