DEV Community

akbhairwal
akbhairwal

Posted on

1

6-10PM challenge problem #005 solution

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());
                  }            
              }           
            }  
  }

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free โ†’

๐Ÿ‘‹ Kindness is contagious

Please leave a โค๏ธ or a friendly comment on this post if you found it helpful!

Okay