【问题标题】:Call "Optional#isPresent()" before accessing the value issue with Pageable在使用 Pageable 访问值问题之前调用“Optional#isPresent()”
【发布时间】:2019-05-14 12:28:54
【问题描述】:

我正在使用 Spring Data Mongo PageableSonar 给我以下错误:

Optional<Order> optional = pageable.getSort().stream().findFirst();
if(optional.isPresent()) {
    direction = pageable.getSort().stream().findFirst().get().getDirection();
    property = pageable.getSort().stream().findFirst().get().getProperty();
}

SortOperation sortOperation = Aggregation.sort(direction, property); 

错误:

在访问值之前调用“Optional#isPresent()”。

我尝试了几个选项,但没有任何效果。

【问题讨论】:

    标签: mongodb spring-data-mongodb pageable


    【解决方案1】:

    当您在if 语句中再次调用pageable.getSort().stream() 时,您正在创建一个新的Optional,您需要调用.isPresent()

    您应该重复使用已有的Optional,而不是一遍又一遍地创建流,如下所示:

    Optional<Order> optional = pageable.getSort().stream().findFirst();
    if(optional.isPresent()) {
        direction = optional.get().getDirection();
        property = optional.get().getProperty();
    }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-17
    • 2022-01-17
    • 2019-04-10
    • 2022-01-19
    • 1970-01-01
    • 2016-05-26
    • 2015-11-10
    • 1970-01-01
    相关资源
    最近更新 更多