我试图根据从查询中获得的结果集来创建树结构。仅当结果集有两列时,下面的代码块才有效。第一列是父列,第二列是子列。我遇到的问题是尝试对其进行重新设计,以便它可以包含多个不同的级别(每列代表一个级别)。我现在唯一能做的就是复制代码,检查级别数和硬编码以便添加到新级别。我按行然后列处理结果集。 (例如,获取第一行,然后获取第一列并存储该值。)
有关如何重新设计此功能的任何想法,可以灵活调整其可以达到的级别数量吗?最终,根被传递到HashTable并处理为JSON文件。仅供参考,我在代码的第二部分中进行JSON格式化,遍历HashMap并对其进行格式化以适应我对JSON的需求。
HashMap<String, HashSet<String>> level1TwoColumn = new HashMap<String, HashSet<String>>();
Object[] listElementCalcColumnNumber = list.get(0);
Hashtable allHash = new Hashtable();
//this will store all of the values in a hashmap and hashset
for(int i=0; i<list.size(); i++){
Object[] listElement = list.get(i);
//the reason we added ""+ between (String) and listElement is because listElement can be something other than a String (e.g. double, integer, etc)
//by adding "" to it, it becomes a String value automatically so then we can cast double/integer/etc into a String
String currentLevel1 = (String) ""+listElement[0];
currentLevel1 = currentLevel1.replace("\"", "");
//this prevents variables from duplicating. if the new element does not exist in hashmap, a new record in the hashmap will be created.
if((level1TwoColumn.get(currentLevel1) = null)){
HashSet<String> level2 = new HashSet<String>();
level1TwoColumn.put(currentLevel1, level2);
}
//stores all of the lowest level into a hashset because they're all going to be unique. no need to check to see if they exist in the hashset.
String currentLevel2 = (String) ""+listElement[1];
currentLevel2 = currentLevel2.replace("\"", "");
level1TwoColumn.get(currentLevel1).add(currentLevel2);
}
HashSet completeTree = new HashSet();
//now that the structure of the data is complete. iterate through level1 to get and store keys as values and "name" as key
for(String key1 : level1TwoColumn.keySet()){
HashSet levelOneSet = new HashSet();
HashMap levelOne = new HashMap();
levelOne.put("name", key1);
levelOneSet.add(levelOne);
//this for-statement does the same thing as previous for-statement; stores the unique values and give them "name" and then put them in hashset and give the set a "children" key
for(String key2 : level1TwoColumn.get(key1)){
HashSet levelTwoSet = new HashSet();
HashMap levelTwo = new HashMap();
levelTwo.put("name", key2);
levelTwoSet.add(levelTwo);
levelOne.put("children", levelTwoSet);
}
//once it loops through once, all level 2 items will be stored under a unique level 1. then it gets added into our dendrogram one by one until all level 1 elements are added.
completeTree.add(levelOne);
}
//this is assigning what our first node is, which is "VA"
allHash.put("name", "VA");
//put everything under "VA" node
allHash.put("children", completeTree);