快速使用java8 的Optional減少if else


該類主要用於處理一些可能為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());


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM