@
Junzhou 呃,我是说我写的那个不对啦.
昨天太晚了,改成这样就好了.
import java.util.*;
public class App {
public static void main(String[] args) {
Map<String, Map> map = new HashMap();
String[] cityList = {"中国 浙江 杭州","中国","中国 广东", "中国 广东 广州 越秀区", "中国 达拉崩吧 广州"};
for (String cityStr: cityList) {
Map<String, Map> parentMap = map;
for (String key: cityStr.split(" ")) {
Map mapOfKey = addMap(key, parentMap);
parentMap = mapOfKey;
}
}
System.out.println(toJSON(map, 0));
}
public static Map<String, Map> addMap(String key,Map<String, Map> map ) {
if(!map.containsKey(key)) {
map.put(key, new HashMap<String, Map>());
}
return map.get(key);
}
public static String toJSON(Map<String, Map> map, int intend) {
String str = "{";
List<String> keys = new ArrayList(map.keySet());
if( keys.size() > 0) {
str += "\r\n";
}
for (int i = 0; i < keys.size(); i++) {
String key = keys.get(i);
str += geneSpace(intend + 2) + key + ": " + toJSON(map.get(key), intend + 2);
if(i < keys.size() - 1) {
str += ",";
}
str += "\r\n";
}
if( keys.size() > 0) {
str += geneSpace(intend);
}
str += "}";
return str;
}
public static String geneSpace(int len) {
return new String(new char[len]).replace('\0', ' ');
}
}