該類主要用於處理一些可能為null的變量,而同時避免寫if(xx==null){..} else{..} 這類代碼
首先看入口nullable
/**
* 可以看到Optional已經自動分配了of()/empty()
*/
public static <T> Optional<T> ofNullable(T value) {
return value == null ? empty() : of(value);
}
接下來則是Optional的常見用法,都是一行代碼搞定
TestDemo testDemo = new TestDemo();
//根據testDemo是否為null,為變量設置不同值(不同的返回值)
int count3 = Optional.ofNullable(testDemo).map(item -> item.getCount()).orElse(1);
//testDemo不為null,則對這個對象做操作
Optional.ofNullable(testDemo).ifPresent(item -> {
item.setCount(4);
});
//testDemo為null,則拋出異常
Optional.ofNullable(testDemo).orElseThrow(() -> new Exception());
java8的Map也有類似能力
//原來的代碼
Object key = map.get("key");
if (key == null) {
key = new Object();
map.put("key", key);
}
// 上面的操作可以簡化為一行,若key對應的value為空,會將第二個參數的返回值存入並返回
Object key2 = map.computeIfAbsent("key", k -> new Object());
以下是通過stream手動實現groupby sum(amount)的效果
//手動groupby identificationNum,calRule,orgId
ArrayList<CollectIncomeAmountResult> collectResults = new ArrayList<>(incomeAmounts.stream().collect(Collectors.toMap(k -> k.getIdentificationNum() + k.getCalRule() + k.getOrgId(), a -> a, (o1, o2) -> {
o1.setAmount(o1.getAmount().add(o2.getAmount()));
return o1;
})).values());