每个客户都有一个 id 和许多带有日期的发票,这些发票按 id 存储为客户的 Hashmap,按日期存储为发票的哈希图:
HashMap<LocalDateTime, Invoice> allInvoices = allInvoicesAllClients.get(id);
if(allInvoices!=null){
allInvoices.put(date, invoice); //<---REPEATED CODE
}else{
allInvoices = new HashMap<>();
allInvoices.put(date, invoice); //<---REPEATED CODE
allInvoicesAllClients.put(id, allInvoices);
}
Java的解决办法好像是用
getOrDefault
:HashMap<LocalDateTime, Invoice> allInvoices = allInvoicesAllClients.getOrDefault(
id,
new HashMap<LocalDateTime, Invoice> (){{ put(date, invoice); }}
);
但是如果 get 不为空,我仍然希望 put (date, invoice) 执行,并且仍然需要向“allInvoicesAllClients”添加数据。所以它似乎没有多大帮助。
最佳答案
这是 Map#computeIfAbsent
的绝佳用例.您的代码段本质上等同于:
allInvoicesAllClients.computeIfAbsent(id, key -> new HashMap<>()).put(date, invoice);
如
id
不在 allInvoicesAllClients
中作为键出现,然后它会从 id
创建映射到新 HashMap
并返回新的 HashMap
.如 id
作为键存在,那么它将返回现有的 HashMap
.
关于java - 如何避免重复代码初始化 hashmap 的 hashmap?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60763355/