我正在尝试遍历哈希图列表并形成树状结构。输入(哈希图列表)和所需的输出(哈希图列表)如下:
输入:
[{State=Tamil Nadu, Continent=Asia, Country=India, City=Chennai}, {State=Kerala, Continent=Asia, Country=India, City=Cochin}, {State=Tamil Nadu, Continent=Asia, Country=India, City=Madurai}, {State=Something, Continent=Asia, Country=Srilanka, City=Colombo}, {State=anythig, Continent=Africa, Country=South Africa, City=new}]
预期结果:
[{children=[{children=[{State=Tamilnadu, children=[{City=Madurai}, {City=Chennai}]}, {State=Kerala, children=[{City=Cochin}]}], Country=India}, {Country=Srilanka}], Continent=Asia}, {Continent=Africa}]
(请考虑即使是斯里兰卡和非洲也应该具有相同的结构。我没有添加,因为它是一个样本)
主要目的是形成一个树状结构,如下所示:
Asia
India
TamilNadu
Chennai
Madurai
Kerala
Cochin
Srilanka
Something
Colombo
Africa
South Africa
Anything
new
所有数据都是动态的,唯一给定的输入将是组顺序,这就像"Continent, Country, State, City"
意味着城市属于州,州属于国家等等。我在下面的代码中尝试的是搜索输入列表,首先获取城市,形成城市地图,然后找到地图包含每个城市的值的索引列表并获取状态,将它们添加到一张地图并在关键状态下添加相应的城市children
(我想以递归方式进行但无法得到一个想法),这很重要,因为最终的地图列表将被转换为一棵树的 json 输入店铺。这必须在 java 代码中完成,我对此感到震惊。任何人都可以提供样本或任何指针...
public void recursiveSearch(List<Map<String, String>> inputList){
String groupOrder = "Continent, Country, State, City";
String[] splitList = groupOrder.split(",");
Map finalMap = new HashMap();
for(int i= splitList.length-1; i >= 0; i--){
//int index = 0;
List searchList = new ArrayList();
String keyToSearch= splitList[i].trim();
for (Map<String, String> map : inputList) {
String searchVal= map.get(keyToSearch);
//index = inputList.indexOf(map);
//System.out.println(index);
if(!searchList.contains(searchVal)){
searchList.add(searchVal);
}
//System.out.println(searchVal);
}
if(searchList.size() > 0){
Map allSearchMap = new HashMap();
Map indSearchMap= new HashMap();
for(int j=0; j < searchList.size(); j++ ){
int index = 0;
//System.out.println(splitList[splitList.length-1] +" "+ keyToSearch);
if(((splitList[splitList.length-1]).trim()).equalsIgnoreCase(keyToSearch)){
Map indexMap = new HashMap();
for (Map<String, String> newMap : inputList) {
boolean result= newMap.containsValue(searchList.get(j));
if(result){
index = inputList.indexOf(newMap);
System.out.println(searchList.get(j)+ " "+index);
}
}
indexMap.putAll(inputList.get(index));
if(indexMap != null){
if(!indSearchMap.containsValue(searchList.get(j))){
indSearchMap.put(keyToSearch, searchList.get(j));
}
allSearchMap.put(keyToSearch+j, indSearchMap);
if(i-1 >= 0){
String parent = (String) indexMap.get(splitList[i-1].trim());
finalMap.put(splitList[i-1].trim(), parent);
finalMap.put("children", allSearchMap.get(keyToSearch+j));
//System.out.println(index+ " "+searchList.get(j)+" "+indexMap.get(splitList[i-1].trim()));
}
}
}
}
}
}
System.out.println("--->"+finalMap.toString());
}
NOTE: The data and the group order are dynamic and can be of anything or any count.