如何填充我的HashMap / keySet()?

时间:2016-11-12 03:09:36

标签: java hashmap

如果keySet()方法包含来自getWordArray方法的单词,我已设法设置填充的HashMap。这工作正常并且编译,但我面临的问题是我的HashMap.keySet()没有填充它应该是什么。给我的指示清单如下:

  • 使用keySet()来检索键集(映射的String部分)。循环遍历此集并打印出单词及其计数。
  • 使用getWordSet()方法完成WordGroup中所有单词的完整设置。
  • 遍历新的HashSet,打印所有单词的完整列表,其中包含每个哈希映射的总和计数。

我对如何检索密钥集感到困惑,在HashMap上循环,然后打印出带有计数的单词。任何有关如何做到这一点的帮助非常感谢,谢谢。附:到目前为止我的代码:

WordGroup类

package lab5;
import java.util.HashSet;
import java.util.Set;
import java.util.HashMap;

public class WordGroup {

    String  word;

    // Creates constructor which stores a string value in variable "word" and converts this into lower case using
    // the lower case method.
    public WordGroup(String aString) {

        this.word = aString.toLowerCase();
    }

    public String[] getWordArray() {

        String[] wordArray = word.split("-");
        return wordArray;
    }
    public Set<String> getWordSet(WordGroup secondWordGroup) {

 HashSet<String> newHashSet = new HashSet<>();

for (String word : secondWordGroup.getWordArray())
    newHashSet.add(word);

for (String word : this.getWordArray())
    newHashSet.add(word);
System.out.println(newHashSet);
return newHashSet;

}

    public HashMap<String, Integer> getWordCountsMap() {

        HashMap<String, Integer> myHashMap = new HashMap<String, Integer>();

        for (String word : this.getWordArray()) {
            if (myHashMap.keySet().contains(word)) {
                myHashMap.put(word, myHashMap.get(word) + 1);
            } else {
                myHashMap.put(word, 1);
            }

        }

        return myHashMap;
    }
}

主要课程

package QuestionEditor;
public class Main{
    public static void main (String[] args) {
        WordGroup firstWordGroup = new WordGroup("You-can-discover-more-about-a-person-in-an-hour-of-plau-tban-in-a-year-of-conversation");
        WordGroup secondWordGroup = new WordGroup ("When-you-play-play-hard-when-you-work-dont-play-at-all");

        System.out.println("*****First Array list*****");
        String[] firstWordArray =  firstWordGroup.getWordArray();
           for( String word : firstWordArray) { 
              System.out.println(word);
        }
        System.out.println("*****Second Array list*****");
        String[] secondWordArray =  secondWordGroup.getWordArray();
           for( String word : secondWordArray) { 
              System.out.println(word); 
        }


         for (String pp : secondWordGroup.getWordSet(secondWordGroup)) {
         System.out.println(pp);
    }
         System.out.println("swdadwdawd");
         for (String pp : firstWordGroup.getWordSet(firstWordGroup)) {
         System.out.println(pp);
    }
         System.out.println("*************************");
         secondWordGroup.getWordCountsMap();
         System.out.println("*************************");
         secondWordGroup.test();
        }
    }

0 个答案:

没有答案