2015-04-17 49 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()); 
相关问题