2015-04-17 48 views
0

感謝您閱讀我的文章。目前我正在做一個學校項目,不幸的是卡住了。我有一個我希望能夠遍歷並放入數組/列表結構的類型的散列圖。而不是使用Map.Entry,我有一個輔助類來使代碼不那麼棘手(即時通訊仍然被欺騙)。如何迭代哈希映射並放入數組/列表結構?

助手類:

class WordCount { 

     String word; 
     Integer count; 

     WordCount(String word, Integer count) { 
      this.word = word; 
      this.count = count; 
     } 
    } 

,我已經試過這樣:

WordCount[] wc = new WordCount[hm.size()]; 
Iterator it = hm.entrySet().iterator(); 
int i = 0; 
while (it.hasNext()) { 
    Map.Entry pair = (Map.Entry) it.next(); 
    wc[i].word = (String) pair.getKey(); 
    wc[i].count = (Integer) pair.getValue(); 
    i++; 
} 

我得到的錯誤與然而該代碼。我有一種感覺,有一種更簡單的方法去這個...

+0

爲什麼使用原始類型?泛型將消除大量這些強制類型,並使代碼更容易出錯。 – user2357112

+0

你的hashmap是否有字符串字作爲鍵和int計數值?還是你有一個類對象而不是HashMap? –

+1

如果您有任何例外或錯誤,請不要忘記將它們添加到問題中。 – Ian2thedv

回答

0
List<WordCount> wordcounts = new ArrayList<>(); 

for (String s : hm.keySet()) { 
    int count = hm.get(s); 
    WordCount w = new WordCount(s,count); 
    wordcounts.add(w); 
} 
3

如果你想的Hashmap i的值能想到的最簡單的方法轉移到一個數組是

ArrayList<Elements> list = 
    new ArrayList<Elements>(myHashMap.values()); 
1

在java 8中:

List<WordCount> words = hm.entrySet().stream() 
          .map(e -> new WordCount(e.getKey(), e.getValue())) 
          .collect(Collectors.toList()); 
相關問題