HashMap迭代器/ForEach循环

HashMap迭代器/ForEach循环,foreach,iterator,hashmap,return,main,Foreach,Iterator,Hashmap,Return,Main,只是一个关于HashMaps的简单问题。基本上我有两条弦。两者在每个字符串中都有一定数量的相似单词。下面的HashMap方法允许我计算某个单词在每个句子中出现的次数。我的问题是在main方法中返回这个方法。HashMap方法如下所示: public HashMap<String, Integer> getWordCounts(){ HashMap<String, Integer> map = new HashMap<String, Integer>()

只是一个关于HashMaps的简单问题。基本上我有两条弦。两者在每个字符串中都有一定数量的相似单词。下面的HashMap方法允许我计算某个单词在每个句子中出现的次数。我的问题是在main方法中返回这个方法。HashMap方法如下所示:

public HashMap<String, Integer> getWordCounts(){
    HashMap<String, Integer> map = new HashMap<String, Integer>();

    for (int i = 0; i < this.getWordArray().length; i++){
        String key = getWordArray()[i];
        Integer count = map.get(key);

        if(count == null){ 
            count = 1;
        }else{
            count++; 
        }   

        map.put(key, count);

    }
        return map;
}
public HashMap getWordCounts(){
HashMap=newHashMap();
for(int i=0;i
这就是我到目前为止得到的返回方法

        HashMap<String, Integer> hashMapAdd = map.getWordCounts();
    for(HashMap.Entry <String, Integer> entry : plato.entrySet()){
        System.out.println(entry.getKey()+ "," + entry.getValue());
    }
HashMap hashMapAdd=map.getWordCounts();
for(HashMap.Entry:plato.entrySet()){
System.out.println(entry.getKey()+”,“+entry.getValue());
}
我的返回方法是否正确?我觉得我走错方向了


谢谢大家

除了函数的逻辑(我没有分析它),关于你问的问题……
是的,这种方法完全可以在java中构造和返回像这样的哈希图,当我在C++上工作了2年后开始使用java,我有时也会感到困惑,但我不知道在java中返回本地对象是完全正确的,因为JVM的垃圾收集器使用这种技术处理可能出现在C++中的问题。 现在,您得到了hashmap,要迭代并打印hashmap,只需使用如下循环:

for(String key:hashMapAdd.keySet())
     System.out.println(key+ "," + hashMapAdd.get(key));
至少对我来说,这不那么容易混淆。 有关HashMap的详细信息,请访问:


注:我假设您的代码正在编译(您没有抱怨任何编译错误),因为linemap.getWordCounts();看起来很可疑,我假设这个方法在某个名为map的类中。但在这种情况下,您将无法使用名称映射制作HashMap,您需要了解为什么在这一行代码中使用map。

您能澄清您的问题吗?是的,我不确定如何从HashMap打印结果。这个hashmap在另一个类中,我想在一个单独的主类中打印结果。
map
变量是什么?它是哪种类型的?哪个类包含
getWordCounts
方法?