记一次Optional导致的 java.util.NoSuchElementException: No value present

在跑任务的时候,代码

Optional comSizeMaxCompanyComSizeBean  = entrySet.getValue().stream()
                        .filter(bean -> bean.getComSizeMax() >= finalComSizeMin)
                        .collect(Collectors.minBy(Comparator.comparing(CompanyComSizeBean::getComSizeMax)));

                if(comSizeMaxCompanyComSizeBean != null ){
                    CompanyComSizeBean companyComSizeBean = comSizeMaxCompanyComSizeBean.get();
                    comSizeMax = companyComSizeBean.getComSizeMin();
                }

出现以下异常:

java.util.NoSuchElementException: No value present
	at java.util.Optional.get(Optional.java:135)

经查询博客Java 8 Optional类深度解析发现,究其原因为: 

//在空的Optional实例上调用get(),抛出NoSuchElementException

更正代码如下:

Optional comSizeMaxCompanyComSizeBean  = entrySet.getValue().stream()
                        .filter(bean -> bean.getComSizeMax() >= finalComSizeMin)
                        .collect(Collectors.minBy(Comparator.comparing(CompanyComSizeBean::getComSizeMax)));

                if(comSizeMaxCompanyComSizeBean != null && comSizeMaxCompanyComSizeBean.isPresent()){
                    CompanyComSizeBean companyComSizeBean = comSizeMaxCompanyComSizeBean.get();
                    comSizeMax = companyComSizeBean.getComSizeMin();
                }

查询博客地址:https://www.cnblogs.com/xingzc/p/5778090.html

你可能感兴趣的:(记一次Optional导致的 java.util.NoSuchElementException: No value present)