我正在尝试存储一条单词在推文流中的总使用次数。每收到一条推文,我都会将它分成一个数组,然后迭代数组以将每个单词添加到hashmap,或者如果它已经存在,则增加它的值。我的问题是,每次收到推文时hashmap都显示为空白。每当我添加一组新数据时Java Hashmap会被清除
private HashMap<String, Integer> map;
private void createDataStore() {
map = new HashMap<String, Integer>();
}
protected void addKeywords(Status status) {
// get tweet
String str = status.getText();
// split into an array
String[] splited = str.split("\\s+");
// vars used in loop
String thisStr;
int wordTot;
for (int i = 0; i < splited.length; i++) {
// get word from array
thisStr = splited[i];
// check if the word is in the hashmap
if (!map.containsKey(thisStr)) {
// already exists
map.put(thisStr, 1);
} else {
// its a new word!
wordTot = map.get(thisStr);
wordTot++;
map.put(thisStr, wordTot);
}
}
}
private void traceTotals() {
System.out.println("trace totals");
Iterator<Entry<String, Integer>> it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry) it.next();
System.out.println(pairs.getKey() + " = " + pairs.getValue());
it.remove(); // avoids a ConcurrentModificationException
}
}
你如何使用这个代码由iterator.this语句返回的最后一个元素删除集合中删除?你是否为每条推文调用'createDataStore'? –
你怎么称呼这三种方法? – Masudul
当然与'HashMap'无关。这种行为主要依赖于方法调用序列和“状态”的内容。只需在'addKeywords()'和'createDataStore()'中添加额外的日志记录,你就会发现问题出在哪里。 –