Tuesday, March 15, 2016

Array of HashMaps in Java

HashMap in Java is one of the common data structures used to store key-value pairs. HashMap can also be used as items of an ordinary array.
package util;

import java.util.HashMap;
import java.util.Map;

public class ArrayUtility {


    @SuppressWarnings("unchecked")
    public static HashMap<String,Object>[] createAndFillHashMapArray( final int size )
    {
        HashMap<String, Object>[] hashMapArray = (HashMap<String, Object>[])new HashMap[size];
        int i = 0;
        for (HashMap<String, Object> hashMap : hashMapArray) {
             hashMap = new HashMap<String, Object>();
             hashMap.put("key"+i, "value"); 
             hashMapArray[i] = hashMap;
             i++;
        }
        return hashMapArray;
    }
 
    public static void displayHashMapArrayContent( HashMap<String, Object>[] hashMapArray )
    {
        if( hashMapArray != null && hashMapArray.length > 0 )
        {
           for (HashMap<String, Object> hashMap : hashMapArray) {
              for (Map.Entry<String, Object> entry : hashMap.entrySet()) {
                  String key = entry.getKey();
                  Object value = entry.getValue();
                  System.out.println(key+" - "+value);
               }
           }
         }
    }
 
    public static void main(String[] args) {
  
         HashMap<String, Object>[] hashMapArray = createAndFillHashMapArray(5);
         displayHashMapArrayContent(hashMapArray);
    }
}


createAndFillHashMapArray method takes the size of the array and fills it with HashMaps.
displayHashMapArrayContent method takes the hashMap array and displays its content as follows :

key0 - value
key1 - value
key2 - value
key3 - value
key4 - value