collectlist()返回一个空列表,不输入defaultifempty

rkttyhzu  于 2021-06-27  发布在  Java
关注(0)|答案(1)|浏览(332)

我有以下代码:

@GetMapping("/enrollment/{id}")
public Mono<ResponseEntity<Response>> findByEnrollment(@PathVariable("id") String enrollment){
    return Mono.just(enrollment)
               .flatMap(e -> technomechanicalService.findByEnrollmentVehicle(e)
                                                    .collectList()
                                                    .map(t -> ResponseEntity.ok()
                                                                            .body(new Response(t, HttpStatus.OK.value(), null)))
                                                    .defaultIfEmpty(new ResponseEntity<>(new Response(null, HttpStatus.BAD_REQUEST.value(), "No se encontro la placa!"), 
                                                                            HttpStatus.BAD_REQUEST)));

}

当使用mongodb中不存在的值从客户机( Postman )消费时,它不会转到defaultifempty。
我给你的解决方案是在Map之前添加一个过滤器。如下所示:

@GetMapping("/enrollment/{id}")
public Mono<ResponseEntity<Response>> findByEnrollment(@PathVariable("id") String enrollment){
    return Mono.just(enrollment)
               .flatMap(e -> technomechanicalService.findByEnrollmentVehicle(e)
                                                    .collectList()
                                                    .filter(t -> {
                                                        if(!t.isEmpty()) return true;
                                                        return false;
                                                    })
                                                    .map(t -> ResponseEntity.ok()
                                                                            .body(new Response(t, HttpStatus.OK.value(), null)))
                                                    .defaultIfEmpty(new ResponseEntity<>(new Response(null, HttpStatus.BAD_REQUEST.value(), null), 
                                                                            HttpStatus.BAD_REQUEST)));

}

我的问题是.defaultifempty()会去哪里?

hpxqektj

hpxqektj1#

defaultIfEmpty() 下班后不工作 .collectList() 因为 .collectList() 用空列表返回mono不等于空,所以 defaultIfEmpty() 不起作用。
你可以改变你的方法顺序,但你的Map方法会工作之后 defaultIfEmpty() 方法

相关问题