有效地使用Optional
类意味着你需要对如何处理潜在缺失值进行全面反思。
10.4.1 用Optional封装可能为null的值
对于可能为null的值使用Optional
包装一下。
HashMap<String, String> map = new HashMap<>();
String value = map.get("anan"); // value值可能为null, 可以使用Optional包装一下
Optional<String> optionalS = Optional.ofNullable(map.get("anan"));
10.4.2 异常与Optional的对比
由于某种原因,函数无法返回某个值,这时除了返回null,还可以抛出一个异常。
// int i = Integer.parseInt("an"); // 抛出一个异常
public static Optional<Integer> StringToInteger(String str) {
try {
return Optional.of(Integer.parseInt(str));
} catch (NumberFormatException e) {
return Optional.empty();;
}
}
10.4.3 把所有内容整合起来
Properties properties = new Properties();
properties.setProperty("anan", "5");
properties.setProperty("qimy", "true");
properties.setProperty("qyuh", "-10");
public static int readDuration(Properties prop, String key) {
String property = prop.getProperty(key);
try {
int parsed = Integer.parseInt(property);
if (parsed > 0) {
return parsed;
}
} catch (NumberFormatException e) {
} return 0;
}
将readDuration
方法用Optional
重构一下。