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<String, ArrayList<Integer>ArrayList<Integer>> 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.
- If it does not exist, one will be created and returned by the lambda expression.
- If it exists, then the value for the key will be returned by
computeIfAbsent().
Really elegant! 👍