How can I avoid repeating code initializing a hashmap of hashmap?
This is an excellent use-case for Map#computeIfAbsent
. Your snippet is essentially equivalent to:
allInvoicesAllClients.computeIfAbsent(id, key -> new HashMap<>()).put(date, invoice);
If id
isn't present as a key in allInvoicesAllClients
, then it'll create mapping from id
to a new HashMap
and return the new HashMap
. If id
is present as a key, then it'll return the existing HashMap
.
computeIfAbsent
is a great solution for this particular case. In general, I'd like to note the following, since nobody mentioned it yet:
The "outer" hashmap just stores a reference to the "inner" hashmap, so you can just reorder the operations to avoid the code duplication:
HashMap<LocalDateTime, Invoice> allInvoices = allInvoicesAllClients.get(id);
if (allInvoices == null) {
allInvoices = new HashMap<>();
allInvoicesAllClients.put(id, allInvoices);
}
allInvoices.put(date, invoice); // <--- no longer repeated