loading...

6-10PM challenge problem #005 solution

akbhairwal profile image akbhairwal ・1 min read

Flatten a Dictionary

Solution for the Problem#005 is provided in Java language.

Test cases :

Test case #1
input: {"Key1":"1","Key2":{"a":"2","b":"3","c":{"d":"3","e":"1"}}}

Test case #2
input:{"Key":{"a":"2","b":"3"}}

Test case #3
input: {"Key1":"1","Key2":{"a":"2","b":"3","c":{"d":"3","e":{"f":"4"}}}}

Test case #4
input : {"":{"a":"1"},"b":"3"}

Test case #5
input :
{"a":{"b":{"c":{"d":{"e":{"f":{"":"awesome"}}}}}}}

Test case #6
input : {"a":"1"}

Solution



static HashMap flattenDictionary(HashMap dict) {   
   HashMap out = new HashMap();
        putAllFlat(out, "", dict);
        return out;
  }
  
  
  static void putAllFlat(HashMapout, String key, Object dictMap) {
    HashMap objMap = (HashMap) dictMap;     
        for(Map.Entry eleMap : objMap.entrySet()){            
               if(eleMap.getValue() instanceof HashMap){
                   if(key.length()>0) {
                       putAllFlat(out, key+"."+eleMap.getKey(), eleMap.getValue());
                   }else {
                       putAllFlat(out, eleMap.getKey(), eleMap.getValue());
                   }
               
              }else {
                  if(eleMap.getKey().length()>0) {
                      if(key.length()>0) {
                          out.put(key+"."+eleMap.getKey(),eleMap.getValue().toString());
                      }else {
                          out.put(eleMap.getKey(),eleMap.getValue().toString());
                      }                   
                  }else {
                      
out.put(key,eleMap.getValue().toString());
                  }            
              }           
            }  
  }

Posted on Jun 2 by:

Discussion

markdown guide