如何使用 Java 8 上述情况可选?

How to use Java 8 Optional for mentioned situation?

假设我有一个 pojo Medicine,

class Medicine{
    private String xmedicine;
    private String ymedicine;
    private String zmedicine;

    //getter and setter here....
}

下面API如果medicine不为null则用来采集药水

public List<Map<String, Object>> gettMedicine(Medicine medicine) {
        List<Map<String, Object>> detailsList = null;

        List<Integer> list = new ArrayList<>();

        if(null != medicine.getXmedicine()){
            list.add(medicine.getXmedicine());                              
        }
        if(null != medicine.getYmedicine()){
            list.add(medicine.getYmedicine());                              
        }
        if(null != medicine.getZmedicine()){
            list.add(medicine.getZmedicine());                              
        }
        if(!CollectionUtils.isEmpty(list)) {
            detailsList = //calling other API to get details from list;
        }
        return detailsList;
}

这里最好使用 java 8 Optional 来消除 NullPointerException 因为我有多个空检查使我的代码样板文件。

如果是,那么你能建议我如何在这里使用 Optional 吗?

您不应将 Optional 用于 class 中的字段,或像在 ifs 中那样将其替换为空检查。在这种情况下,您可以执行以下操作:

Stream.of(medicine.getXmedicine(), medicine.getYmedicine(), medicine.getZmedicine())
       .filter(Objects::nonNull)
       .collect(Collectors.toList())