题目:
给定一个“Flatten” Dictionary 对象其键是点分割的,例如:{"A":1,"B.A":2,"B.B":3,"CC.D.E":4,"CC.D.F":5}
,实现一个函数,将其转换 为一个嵌套的字典对象,根据上面例子,嵌套对象结果为{A:1,"B":{"A":2,"B":3},"CC":{"D":{"E":4,"F":5}}}
答案
/**
* {A:1, B.A:2 B.B:3 CC.D.E:4 CC.DF:5}
* @param args
*/
public static void main(String[] args) {
Map<String, Integer> flatten = new HashMap<>();
//生成例子数据
flatten.put("A",1);
flatten.put("B.A",2);
flatten.put("B.B",3);
flatten.put("CC.D.E",4);
flatten.put("CC.D.F",5);
Map<String, Object> newFlatten = new HashMap<>();
flatten.forEach((key,val)->{
recursion(key,newFlatten, val);
});
System.out.println(flatten);
System.out.println(newFlatten);
}
/**
* 递归方法
* @param key
* @param map
* @param val
*/
public static void recursion(String key ,Map<String,Object> map,Integer val){
boolean contains = key.contains(".");
//最后一个赋值
if(!contains){
map.put(key,val);
}else{
String beforeKey = StrUtil.subBefore(key, ".", false);
String afterKey = StrUtil.subAfter(key, ".", false);
HashMap<String, Object> newMap = new HashMap<>();
if (!map.containsKey(beforeKey)){
map.put(beforeKey,newMap);
}else {
newMap = (HashMap<String, Object>) map.get(beforeKey);
}
recursion(afterKey,newMap,val);
}
}