Is checking for key existence in HashMap always necessary?
I have a HashMap with say a 1000 entries and I am looking at improving the efficiency. If the HashMap is b
You can also use the computeIfAbsent() method in the HashMap class.
In the following example, map stores a list of transactions (integers) that are applied to the key (the name of the bank account). To add 2 transactions of 100 and 200 to checking_account you can write:
HashMap> map = new HashMap<>();
map.computeIfAbsent("checking_account", key -> new ArrayList<>())
.add(100)
.add(200);
This way you don't have to check to see if the key checking_account exists or not.
computeIfAbsent(). Really elegant!