Java8中那些方便又實用的Map函數( 二 )


merge函數可以發現,上面在使用compute匯總金額時,lambda表達式中需要判斷是否是第一次計算key值 , 稍微麻煩了點,而使用merge函數的話 , 可以進一步簡化代碼,如下:
List<Payment> payments = getPayments();Map<Integer, BigDecimal> amountByTypeMap = new HashMap<>();for(Payment payment : payments){amountByTypeMap.merge(payment.getPayTypeId(), payment.getAmount(), BigDecimal::add);}這個函數太簡潔了 , merge的第一個參數是key , 第二個參數是value,第三個參數是值合并函數 。當是第一次計算相應key的值時,直接放入value到map中,后面再次計算時 , 使用值合并函數BigDecimal::add計算出新的匯總值,并放入map中即可 。
putIfAbsent函數putIfAbsent從命名上也能知道作用了,當map中沒有相應key時才put值到map中 , 主要用于如下場景:如將list轉換為map時,若list中有重復值時,put與putIfAbsent的區別如下:

  • put保留最晚插入的數據 。
  • putIfAbsent保留最早插入的數據 。
forEach函數說實話,java中要遍歷map,寫法上是比較啰嗦的,不管是entrySet方式還是keySet方式,如下:
for(Map.Entry<String, BigDecimal> entry: amountByTypeMap.entrySet()){Integer payTypeId = entry.getKey();BigDecimal amount = entry.getValue();System.out.printf("payTypeId: %s, amount: %s \n", payTypeId, amount);}再看看在python或go中的寫法,如下:
for payTypeId, amount in amountByTypeMap.items():print("payTypeId: %s, amount: %s \n" % (payTypeId, amount))可以發現 , 在python中的map遍歷寫法要少寫好幾行代碼呢,不過,雖然java在語法層面上并未支持這種寫法,但使用map的forEach函數,也可以簡化出類似的效果來,如下:
amountByTypeMap.forEach((payTypeId, amount) -> {System.out.printf("payTypeId: %s, amount: %s \n", payTypeId, amount);});總結一直以來,java因代碼編寫太繁瑣而被開發者們所廣泛詬病 , 但從java8開始,從Map、Stream、var、multiline-string再到record,java在代碼編寫層面做了大量的簡化,java似乎開竅了

推薦閱讀