【问题标题】:Flatten a Dictionary展平字典
【发布时间】:2021-02-28 04:02:08
【问题描述】:

给定一个字典 dict,编写一个函数 flattenDictionary 来返回它的扁平化版本。

input:  dict = {
        "Key1" : "1",
        "Key2" : {
            "a" : "2",
            "b" : "3",
            "c" : {
                "d" : "3",
                "e" : {
                    "" : "1"
                }
            }
        }
    }

output: {
        "Key1" : "1",
        "Key2.a" : "2",
        "Key2.b" : "3",
        "Key2.c.d" : "3",
        "Key2.c.e" : "1"
    }

【问题讨论】:

    标签: java hashmap


    【解决方案1】:
    class Solution {
    
     static HashMap<String, String> flattenDictionary(HashMap<String, Object> dict) {
      HashMap<String, String>result = new HashMap<String, String>();
      flattenNesting("", dict, result);
    
      return result;
    
     }
    
        private static void flattenNesting(String parent, Map<String, Object> dict, Map<String, 
     String> result) {
        for (Map.Entry<String, Object> entry : dict.entrySet()) {
            if (entry.getValue() instanceof String) {
                putEntryInResult(parent, result, entry);
            } else {
                flattenNextLevel(parent, result, entry);
            }
        }
    }
    
    
       private static  void flattenNextLevel(String parent, Map<String, String> result, 
       Map.Entry<String, Object> entry) {
        if (parent.isEmpty()) {
            flattenNesting(entry.getKey(), (Map<String, Object>) entry.getValue(), result);
        } else {
            String key = entry.getKey().isEmpty() ? parent : parent + "." + entry.getKey();
            flattenNesting(key, (Map<String, Object>) entry.getValue(), result);
        }
    }
    
    
      private static void putEntryInResult(String parent, Map<String, String> result, 
       Map.Entry<String, Object> entry) {
        if (parent.isEmpty()) {
            result.put(entry.getKey(), entry.getValue().toString());
        } else {
            String key = entry.getKey().isEmpty() ? parent : parent + "." + entry.getKey();
            result.put(key, entry.getValue().toString());
        }
    }
    
    
     public static void main(String[] args) {
        HashMap<String, Object> dict = new HashMap<String, Object>();   
        dict.put("key1", "1");
        HashMap<String, Object> c = new HashMap<String, Object>();
        c.put("d", "3"); c.put("e", "1");
        HashMap<String, Object> key2 = new HashMap<String, Object>();
        key2.put("a", "2"); 
        key2.put("b", "3"); 
        key2.put("c", c);
        dict.put("key2", key2);
      }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-11
      • 2021-12-31
      • 2021-06-02
      • 2018-07-19
      • 2016-09-03
      • 2019-09-30
      相关资源
      最近更新 更多