Must-Know HashMap Initialization tricks in Java

  • Post last modified:March 18, 2023
  • Reading time:3 mins read

Discussing Options to Initialize hashmap with a default value

Introduction

  • Let’s consider we have an array of the array as input. array elements basically represent order_id and product_id with that. So basically for order_id 1, product_id 2 was bought.
int[][] arr = {{1, 2}, {1, 3}, {2, 3}, {2, 2}, {3, 1}};
  • Now let’s say we want to calculate for each product_id which products were bought.
  • Now this problem basically tells us to output something like Key Value, where the key is order_id and the value is a list of products.
  • So for order_id 1 output would be -> { 1 => [2,3] }

External Initialization

        // initialization
        var orderProductMap = new HashMap<Integer, List<Integer>>();
        for ( int[] order : arr ) {
            if (!orderProductMap.containsKey(order[0])) {
                orderProductMap.put(order[0], new ArrayList<>());
            }
        }
  • Once the hashmap is initialized, we can iterate over the array again and for each key, we update our hashmap with the corresponding value.
  • Here are map stores order_id with a list of product_id hence value is a list of integers.
  • Since each key is initialized we can get that list and add any new product_id that we have seen in the array to it.
       Arrays.stream(arr)
                .forEach(o -> {
                    var productList = orderProductMap.get(o[0]);
                    productList.add(o[1]);
                    orderProductMap.put(o[0],productList);
                });
  • Now our map is populated with all the order_id with a list of product_id
orderProductMap.entrySet().forEach(System.out::println);

Inline Initialization

  • We can improve our code with inline initialization.
  • Hashmap provides the getOrDefault method, what it does is that will initialize the hashmap key with the default value if the key is not present in the hashmap already.
  • Now our Hashmap initialization doesn’t need an additional loop to add all the distinct keys with default values. We can do that inline in simple code using getOrDefault where if the key is not initialized, we pass the default initialization value.
 var orderProductMap = new HashMap<Integer, List<Integer>>();
 Arrays.stream(arr)
           .forEach(a -> {
             List<Integer> list = orderProductMap.getOrDefault(a[0], new ArrayList<>());
             list.add(a[1]);
             orderProductMap.put(a[0], list);
             }
            );

Some more example

  • Let’s see some more examples with the getOrDefault method for the initialization of the hashmap.
  • In the below example array element is product_id and quantity bought. and now we have to calculate for each product_id how many quantities have been bought in total.
  • Now when we iterate over each array element we check if the given product_id key is already present in the hashmap if yes then we get the previous value and add the current value to it otherwise we initialize the key with a default value.
int[][] arr = {{1, 2}, {1, 3}, {2, 3}, {2, 2}, {3, 1}};
Map<Integer, Integer> productCountMap = new HashMap<>();
Arrays.stream(arr)
       .forEach(a -> productCountMap.put(a[0],
                        a[1] + productCountMap.getOrDefault(a[0], 0)));
        productCountMap.entrySet().forEach(System.out::println);

Conclusion

  • In this article, we discuss different methods for initializing a hashmap with a default value.
  • getOrDefault is a very handy method to avoid writing hash initializing with for a loop.

Leave a Reply