Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I avoid repeating code initializing a hashmap of hashmap?

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.

like image 393
Hernán Eche Avatar asked Mar 19 '20 18:03

Hernán Eche


People also ask

How do you initialize a HashMap while declaring it?

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"); }};

How do you initialize a map?

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.

What is the difference between HashMap and map in Java?

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.


Video Answer


1 Answers

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.

like image 122
Jacob G. Avatar answered Oct 09 '22 06:10

Jacob G.