日期:2014-05-20 浏览次数:21014 次
public class TextToStruct {
public static void main(String[] args) {
textToMapList();
}
enum STATUS {
WaitForNew, WaitForKey, WaitForValue
}
public static void textToMapList() {
String source = "{\n123\n121\n122\n}\n{\n333\n113\n113\n}\n{\n123\n121\n123\n}\n";
Map<String, List> map = new HashMap<String, List>(); // 存放结果的Map
STATUS status = STATUS.WaitForNew; // 有穷状态自动机的状态标志
List<String> tmp = null; // 存放当前Value的临时List
Scanner sc = new Scanner(source); // 输入源
// 有穷状态自动机
while (sc.hasNextLine()) {
String line = sc.nextLine().trim();
if (line.length() == 0) {
continue; // 空行直接忽略
}
// 状态自动处理器
switch (status) {
case WaitForNew: // 需要处理 {
if ("{".equals(line)) {
status = STATUS.WaitForKey;
} else { // 发现源数据结构错误,需要起始标志 {,但没有得到
throw new RuntimeException("Except {, but get: " + line);
}
break;
case WaitForKey: // 需要处理 Key
if (!map.containsKey(line)) { // 查找是否已经有过该Key
map.put(line, new ArrayList<String>());
}
tmp = map.get(line); // 准备List
status = STATUS.WaitForValue;
break;
case WaitForValue: // 需要处理 值 和 }
if ("}".equals(line)) {
tmp = null;
status = STATUS.WaitForNew;
} else {
tmp.add(line);
}
break;
}
}
// 输出结果
for (String key : map.keySet()) {
System.out.println(key + ": " + map.get(key));
}
}
}