通过以下代码,我能够从表单中获取所有必要的信息,该信息是;
n = 5
p = 0.5
lambda = 0.3
d = 1
n = 8
p = 0.1
d = 1
p = 0.3
我把所有这些信息放在一个 HashMap 中,但我实际需要的是 6 个 hashmap;像这样
Hashmap 1
n = 5
p = 0.5
Hashmap 2
lambda = 0.3
Hashmap 3
d = 1
Hashmap 4
n = 8
p = 0.1
Hashmap 5
d = 1
Hashmap 6
p = 0.3
换句话说,总是当我得到一个 n 作为关键字时,下一个关键字和值也应该存储在这个 Hashmap 中,这个下一个关键字将始终是一个 p。
我知道分割 Hashmap 是不可能的,但我找不到其他方法
非常感谢
public static void main(String[] args ) throws FileNotFoundException, IOException
{
File filename = new File("H:\\NetBeansProjects\\thesis2.0\\src\\thesis2\\pkg0\\txt-files\\formulier.txt");
try (BufferedReader in = new BufferedReader(new FileReader(filename)))
{
HashMap hm = new HashMap();
Pattern p = Pattern.compile("\\s+(\\w+)\\s+([0-9.]+)\\s*");
for (String line; (line = in.readLine()) != null; )
{
Matcher m = p.matcher(line);
if (m.matches())
{
String keyword = m.group(1);
String parameter = m.group(2);
hm.put(m.group(1),m.group(2));
System.out.println(m.group(1) + " = " + m.group(2));
}
}
}
}
最佳答案
您可以使用 List<>
存储Map<>
s,您基本上需要为将其分派(dispatch)到下一个 Map
的值创建一个基于 token 的简单解析器。 .
List<Map<String,String>> motherList = new ArrayList<>();
Map<String,String> workingChild = new HashMap<>();
....
String keyword = m.group(1);
String parameter = m.group(2);
workingChild.put(keyword,parameter);
if(!keyword.equals("n")) {
motherList.add(workingChild);
workingChild = new HashMap<>();
}
我们基本上有 1 个包含所有子映射的 motherlist,对于每个输入关键字和参数,我们将其放入当前的工作映射中,然后将其放入 motherMap
中。仅当最后一个标记不是“n”时。
关于java - 分割正则表达式的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35155711/