Is there a real reason to use Optional.of()?

前端 未结 7 1211
谎友^
谎友^ 2021-01-04 08:23

I\'ve read here why Optional.of() should be used over Optional.ofNullable(), but the answer didn\'t satisfy me at all, so I ask slightly different:

7条回答
  •  天命终不由人
    2021-01-04 08:42

    The other reason to use Optional.of(value) when you know that value can't be null is that if you want to do additional filtering operations on that Optional.

    For example:

    public static long getPageSizeFrom(HttpServletRequest request) {
        return Optional.of(request.getParameter("pageSize"))
                       .filter(StringUtils::isNumeric)
                       .map(Long::valueOf)
                       .filter(page::hasPageSize)
                       .orElse(page::getDefaultPageSize)
    }
    

提交回复
热议问题