我有这样的输入。
0 Overcast Yes 4
0 Rainy Yes 3
0 Sunny No 3
1 Cool No 1
1 Cool Yes 3
我正在尝试将这些数据存储在Hashmap中
{0=[Overcast Yes 4,Rainy Yes 3,Sunny No 3]}
{1=[Cool No 1,Cool Yes 3]}
到目前为止,我所做的是
Map<String, List<String>> mapPart = new HashMap<String, List<String>>();
List<String> tmpList = new ArrayList<String>();
while((partLine = bfpart.readLine())!=null){
String restOfString="";
String[] first = partLine.split(" ");
String firstPart = first[0];
for (int i=1; i<first.length; i++)
{
restOfString += first[i];
restOfString += " ";
}
if(mapPart.isEmpty()){
tmpList.add(restOfString);
mapPart.put(firstPart, tmpList);
}
else{
for (Map.Entry<String, List<String>> entry : mapPart.entrySet()) {
String colId = entry.getKey();
if(colId.equals(firstPart)){
List<String> lst = mapPart.get(colId);
lst.add(restOfString);
mapPart.put(colId,lst);
}
else{ //should we craete a new list
}
}
}
当前输出
map: {0=[Overcast Yes 4 , Rainy No 2 , Sunny No 3 ]}
我正在尝试计算这个等式。
Info(n)=([no.of yes for overcast,no.of No for overcast],[no.of yes for Rainy,no.of no for Rainy],[no.of yes for Sunny,no.of no for Sunny])
Info0([4,0],[3,0],[0,3])/log2
Info1([3,1])/log2
答案 0 :(得分:1)
您不需要遍历整个哈希映射。这是地图的概念,您可以非常有效地按键搜索:
List<String> list = mapPart.get(firstPart);
if (list == null) {
// first time using this index
list = new ArrayList<String>();
mapPart.put(firstPart, list);
}
list.add(restOfString);
(用此代码段替换for (Map.Entry<...
循环)
答案 1 :(得分:0)
有一种更简单/可读的方式
List<String> value = mapPart.get(firstPart); //1. Get the List<String> for the key
if(value == null) { //2. If it doesn't exist, then create and put it against the key
value = new ArrayList<String>();
mapPart.put(first, value);
}
value.add(restOfString); //3. Finally add the values for the key
答案 2 :(得分:0)
HashMap不会根据索引存储值。你不需要那里的索引。你可以这样做。
else{
for (Map.Entry<String, List<String>> entry : mapPart.entrySet()) {
String colId = entry.getKey();
if(colId.equals(firstPart)){
List<String> lst = get(colId);
lst.add(restOfString);
mapPart.put(colId,lst);
}
}