java - 如何避免重复代码初始化 hashmap 的 hashmap?

标签 java java-8 hashmap

每个客户都有一个 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/

相关文章:

Java 多线程适用于 Windows 但不适用于 Ubuntu

java - 应用程序首次启动时应打开对话窗口

java - 从 Java 调用的 SQL Server 中的表变量问题

java - 使用 Java 流将 Java List 转换为另一个

java - 在 HashMap 中使用 ComputeIfAbsent

java - 如何将 Guava HashMultmap 转换为 java.util.Map

java - 枚举、单例和反序列化

java - 将 Java 8 的 Optional 与 Stream::flatMap 一起使用

java - 如何防止java流运行相同的方法两次?

java - 去除重复输出