简体   繁体   English

如何遍历哈希映射并放入数组/列表结构?

[英]How to iterate through Hash Map & put into an array/list structure?

Thank you for reading my post. 感谢您阅读我的帖子。 Currently I am doing a school project and am unfortunately stuck. 目前,我正在做一个学校项目,很不幸。 I have a hashmap of types that I would like to be able to iterate through and put into an array/list structure. 我有一个类型的哈希图,希望能够对其进行迭代并将其放入数组/列表结构中。 Instead of using Map.Entry I have a helper class to make the code a little less tricky (im still tricked). 与使用Map.Entry相比,我有一个帮助器类,使代码的棘手性降低了(我仍然受骗)。

Helper Class: 助手类:

    class WordCount {

        String word;
        Integer count;

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

and I have tried this: 我已经尝试过了

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++;
}

I get errors with that code however. 但是,我在该代码中遇到错误。 I have a feeling there is a much easier way to go about this... 我觉得有一个更简单的方法可以解决这个问题...

If you want to shift the values of Hashmap to an array the easiest way i can think off is 如果您想将Hashmap的值移动到数组,我能想到的最简单的方法是

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

In java 8 : 在Java 8中:

 List<WordCount> words = hm.entrySet().stream()
                            .map(e -> new WordCount(e.getKey(), e.getValue()))
                            .collect(Collectors.toList());
List<WordCount> wordcounts = new ArrayList<>();  

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM