2013-12-08 54 views
2

我正在创建Map Entry键值对的ArrayList。这样我可以存储大量单个词(作为键)并保存它们使用的总次数(作为值)。如何将一个映射项添加到一个ArrayList?

我需要能够按值排序ArrayList,所以我可以通过它们的值排序单词。

我有2个问题:

  1. 我不知道语法映射条目添加到ArrayList
  2. 我不知道如何到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); 
     } 

    } 

} 

- 编辑 - 工作代码 嗨,我已经添加了新的代码映射条目添加到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; 
      } 
      } 
     }); 
} 
+0

如何编写自己的类来存储这些键值?或者[this](http://stackoverflow.com/a/3110644/645270)(实现Map.Entry接口)。它可以使用自定义比较器进行排序(请参阅'Collections.sort')。 – keyser

+2

为什么不直接使用Map来代替使用Map.Entries的ArrayList模拟Map? – user949300

+0

@ user949300我也是这样问自己的。 –

回答

6
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法的合同:

比较它的两个参数的顺序。返回一个负整数 零,或者一个正整数,因为第一个参数小于,等于 到或大于秒。

+0

太好了,谢谢! – alidrongo

+0

嗨,我似乎无法得到比较工作。你可以检查我更新的问题 - 我已经添加了新的东西。谢谢 – alidrongo

+0

'compare'应该返回o1.getKey()。compareTo(o2.getKey());',而不是'返回0;'。 – Radiodef

相关问题