Every client has an id, and many invoices, with dates, stored as Hashmap of clients by id, of a hashmap of invoices by date:
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 solution seems to be to use getOrDefault
:
HashMap<LocalDateTime, Invoice> allInvoices = allInvoicesAllClients.getOrDefault( id, new HashMap<LocalDateTime, Invoice> (){{ put(date, invoice); }} );
But if get is not null, I still want put (date, invoice) to execute, and also adding data to "allInvoicesAllClients" is still needed. So it doesn't seem to help much.
The Static Initializer for a Static HashMap We can also initialize the map using the double-brace syntax: Map<String, String> doubleBraceMap = new HashMap<String, String>() {{ put("key1", "value1"); put("key2", "value2"); }};
One way to initialize a map is to copy contents from another map one after another by using the copy constructor. Syntax: map<string, string>New_Map(old_map); Here, old_map is the map from which contents will be copied into the new_map.
HashMap is a non-synchronized class of the Java Collection Framework that contains null values and keys, whereas Map is a Java interface, which is used to map key-pair values.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With