Fre*_*sen 6 java optional java-8
我知道你不能从 a 返回ifPresent()所以这个例子不起作用:
public boolean checkSomethingIfPresent() {
    mightReturnAString().ifPresent((item) -> {
        if (item.equals("something")) {
            // Do some other stuff like use "something" in API calls
            return true; // Does not compile
        }
    });
    return false;
}
哪里mightReturnAString() 可以返回一个有效的字符串或一个空的可选。我所做的有效的是:
public boolean checkSomethingIsPresent() {
    Optional<String> result = mightReturnAString();
    if (result.isPresent()) {
        String item = result.get();
        if (item.equals("something") {
            // Do some other stuff like use "something" in API calls
            return true;
        }
    }
    return false;
}
这更长并且与首先检查空值没有太大区别。我觉得必须有一种更简洁的方式来使用 Optional。
我认为您所寻找的只是简单地filter检查是否存在:
return result.filter(a -> a.equals("something")).isPresent();
映射到布尔值怎么样?
public boolean checkSomethingIfPresent() {
    return mightReturnAString().map(item -> {
        if (item.equals("something")) {
            // Do some other stuff like use "something" in API calls
            return true; // Does compile
        }
        return false; // or null
    }).orElse(false);
}
| 归档时间: | 
 | 
| 查看次数: | 10532 次 | 
| 最近记录: |