[英]HashMap of hashMap
我有这个内容:
氢化锂:Li 1 H 1#注释...
我想要以下结果:
{氢化锂':{'Li':1,'H':1},...}
我这样做:
public static HashMap<String,HashMap<String,Integer>> readFormulas(String content){
HashMap<String,Integer> dictionnaire1 = new HashMap<String,Integer>();
HashMap<String,HashMap<String,Integer>> dictionnaire2 = new HashMap<String,HashMap<String,Integer>>();
ArrayList <String> al = new ArrayList<String>();
al.add(Arrays.toString(content.split(":")));// on met chaque ligne dans un tableau
String str[] = content.split("\n");
for(int i = 0 ; i < str.length;i++){//pour chaque ligne
String str2 [] = str[i].split(":");// séparer les noms des molécules des noms scientiques et des commentaires ["Helium","he 1 #fzefzezfezfz"
String NomMolecule = str2[0];
String diese [] = str2[1].split("#");
String description [] = diese[0].split(" ");
int nb = Integer.parseInt(description[2]);
dictionnaire1.put(description[1], nb);
}
dictionnaire2.put(NomMolecule,dictionnaire1);
}
return(dictionnaire2);
}
但是结果不好,我不明白为什么? :条目:
HashMap<String,HashMap<String,Integer>> formulas = readFormulas("helium : he 3 #fsdfsfsdfsf" + "\n" + "lithium hydride : Li 1 H 1 #fdvdfdfvd");
结果:
{氢化锂= {he = 3,Li = 1},氦气= {he = 3,Li = 1}}
每个分子需要一个HashMap:
for(int i = 0 ; i < str.length;i++){//pour chaque ligne
String str2 [] = str[i].split(":");
String NomMolecule = str2[0];
String diese [] = str2[1].split("#");
String description [] = diese[0].trim().split(" ");
HashMap<String,Integer> dictionnaire1 = new HashMap<>();
for( int j = 0; j < description.length; j += 2 ){
int nb = Integer.parseInt(description[j+1]);
dictionnaire1.put(description[j], nb);
}
dictionnaire2.put(NomMolecule,dictionnaire1);
}
您还错过了我添加的分子成分(例如Li 1 H 1)上的环。
HashMap<String,Integer> dictionnaire1 = new HashMap<String,Integer>();
由于此HashMap
在每次循环迭代中都被重用,所以map的先前(陈旧)元素将产生错误的输出。
说明:
在第一次迭代中,字典1: {he:3}
在第二次迭代中,相同的映射将与早期归档的数据一起重用。
找到数据项- {Li: 1}
& {he:3}
这样,您得到了结果。 {Li: 1,he:3}
要获得理想的结果:
首先,您需要在每次迭代中清除dictionnaire1
所有先前条目。
其次,您需要对逻辑进行一些调整,以便从description
数组中检索多个元素-
for(int j=1;j<description.length-1;j+=2){
int nb = Integer.parseInt(description[j+1]);
dictionnaire1.put(description[j], nb);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.