我试图用Java做一些事情,但我遇到了这个问题,我真的不知道如何转换它。我试过循环,但我需要做很多for循环,我想保持我的代码干净。
我有一张看起来像这样的地图。
Map 1:
A: Object
B: Object
C: Map 2
D: Object
E: Object
F: Map 3
G: Object
(Here could be another map that could go really far, etc)
H: Map 4
I: Object
J: Object
(Here could also be more)\
K: Object
(Here could also be more)
请注意,这只是一个示例,地图,密钥等的数量可能会有所不同,因此密钥名称也可能不同。键名不能包含点。
C,F和H是地图C包含D,E,F,H,K和地图F包含G等的地图。
如何将此转换为ONE Map,如下所示:
A: Object
B: Object
C.D: Object
C.E: Object
C.K: Object
C.F.G: Object
C.H.I: Object
C.H.J: Object
按键的顺序无关紧要。
答案 0 :(得分:1)
像这样:
Map<String, Object> converted = convert(input, "");
现在你在输入地图上调用它:
{{1}}
答案 1 :(得分:0)
尝试沿着这些方向行事 让我们说你的地图是 图
public class ObjectMapper
{
Map<Integer,Object> subMap;
}
承认您的对象可以是字符串或地图 假设你调用这样一个对象的“路径” “1#2#4#5”
Map<Integer, Object> someMap;
//assign map or load it from somewhere
String searchPath = "1#2#4#5";
String[] splitPath = searchPath .split("#");
String searchResult = null;
boolean resultFound = false;
boolean resultWrongPlace = false;
Map<Integer, Object> mapToSearch = null;
for(int i = 0; i < splitPath.length; i++)
{
if (resultFound == true)
{
resultWrongPlace = true;
break;
}
if (i == 0)
{
mapToSearch = someMap;
}
Object currentObj = mapToSearch.get(splitPath[Integer.parseInt(splitPath[i])])
if (currentObj instanceof String)
{
searchResult = (String) currentObj ;
resultFound = true;
}
else if (currentObj instanceof ObjectMapper)
{
mapToSearch = (ObjectMapper) currentObj ;
resultFound = false;
}
}
if (resultFound == true && resultWrongPlace == true)
{
throw new Exception("result was found but the path that lead to a result was different from the indended path!");
}
else if (resultFound == false)
{
throw new Exception("no result was found searching your expression path!");
}
我会说这些话会有什么作用