简体   繁体   English

使用HashMap(String,ArrayList <String> )

[英]Using HashMap(String, ArrayList<String>)

I am trying to make the program read four .txt files and count the words in those files. 我试图使程序读取四个.txt文件并计算这些文件中的单词数。

private HashMap<String, ArrayList<String>> mapWords = new HashMap<String, ArrayList<String>>();

public void countWordsInFiles() {
    buildWordFileMap();
}

private void buildWordFileMap() {
    mapWords.clear();
    String[] files = {"brief1.txt","brief2.txt","brief3.txt","brief4.txt"};

    for(int i=0; i<files.length; i++){
        FileResource resource = new FileResource("data/" + files[i]);
        addWordsFromFile(resource); 
    }
}

private void addWordsFromFile(FileResource resource) {
    for(String word : resource.words()){
        word = word.toLowerCase();

        if (mapWords.keySet().contains(word)){
            mapWords.put(word, //Not sure how to use arraylist here);
        }
        else {
            mapWords.put(word, //Not sure how to use arraylist here);
        }
    }
}

The problem is I'm not sure how to make the "if" in the method "addWordsFromFile". 问题是我不确定如何在方法“ addWordsFromFile”中创建“ if”。 Basically, I want my output to be something like this: 基本上,我希望我的输出是这样的:

The greatest number of files a word appears in is three, and there are two such words: “cats” and “and”. 一个单词出现的最大文件数是三个,并且有两个这样的单词:“ cats”和“ and”。

“cats” appears in the files: brief1.txt, brief3.txt, brief4.txt “ cats”出现在文件中:brief1.txt,brief3.txt,brief4.txt

“and” appears in the files: brief1.txt, brief3.txt, brief4.txt “ and”出现在文件中:brief1.txt,brief3.txt,brief4.txt

put a new ArrayList if the key was not found. 如果找不到密钥,则放置一个新的ArrayList。 Afterwards use the arraylist: 然后使用arraylist:

private void addWordsFromFile(FileResource resource, String fileName) {
    for(String word : resource.words()){
        word = word.toLowerCase();

        //Make sure key exists and ArrayList is initialized:
        if (!mapWords.containsKey(word)){
            mapWords.put(word, new ArrayList<String>());
        }

        //Add filename to word's ArrayList if filename wasn't added before:
        if (!mapWords.get(word).contains(fileName)) {
            mapWords.get(word).add(fileName);
        }
    }
}

Consider using a Guava MultiMap so that you don't have to worry about checking for the null ArrayList and maintenance. 考虑使用Guava MultiMap,这样您就不必担心检查空ArrayList和维护。 Now you only have two lines of code to write 现在您只需要编写两行代码

ListMultimap<String, String> mapWords = ArrayListMultimap.create();
//assuming resource has a way to get the file name    
mapWords.put(word, resource.getFileName());

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

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