[英]How can I add an Map Entry to an ArrayList?
我正在創建Map Entry鍵值對的ArrayList。 這樣我就可以存儲大量單個單詞(作為鍵)並保存它們的總次數(作為值)。
我需要能夠按值對ArrayList進行排序,以便我可以按其值排序單詞。
我有兩個問題:
任何幫助非常感謝!
protected void addKeywords(Status status) {
// get tweet
String str = status.getText();
// split into an array remove punctuation and make lower case
String[] splited = str.replaceAll("[^a-zA-Z ]", "").toLowerCase()
.split("\\s+");
// vars used in loop
String thisStr;
int wordTot;
Entry<String, Integer> newEntry = null;
for (int i = 0; i < splited.length; i++) {
// get word from array
thisStr = splited[i].toLowerCase();
thisStr = "hi";
// if this is the first word to be added
if (mapList.size() == 0) {
//this is the syntax that I don't know!
newEntry.key = theStr;
newEntry.value = 1;
mapList.add(newEntry);
} else {
boolean alreadyExists = false;
//iterate through mapList
for (Entry<String, Integer> entry : mapList) {
// already exists
if (entry.getKey() == thisStr) {
wordTot = entry.getValue();
//increment the value
wordTot++;
entry.setValue(wordTot);
break;
}
}
//if we have reached here the value must not be in the arraylist so add it
//again - this is the syntax that I don't know!
newEntry.key = theStr;
newEntry.value = 1;
mapList.add(newEntry);
}
}
}
-EDIT - 工作代碼嗨,我添加了新的代碼,將地圖條目添加到ArrayList,這很有效。
我還更新了我的排序代碼,這也很有效:
private void sortMap() {
Collections.sort(mapList, new Comparator<Map.Entry<String, Integer>>() {
@Override
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
if (o1.getValue()>o2.getValue()){
return 1;
}else if (o1.getValue()<o2.getValue()){
return -1;
}else{
return 0;
}
}
});
}
List<Map.Entry<String, String>> list = new ArrayList<Map.Entry<String, String>>();
list.add(new AbstractMap.SimpleEntry<String, String>("foo", "bar"));
Collections.sort(list, new Comparator<Map.Entry<String, String>>() {
@Override
public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) {
return 0;
}
});
考慮compare
方法的合同:
比較它的兩個參數的順序。 返回負整數,零或正整數,因為第一個參數小於,等於或大於第二個參數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.