java - 使用 HashMap(String, ArrayList<String>)

标签 java

我试图让程序读取四个 .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);
        }
    }
}

问题是我不确定如何在“addWordsFromFile”方法中创建“if”。 基本上,我希望我的输出是这样的:

The greatest number of files a word appears in is three, and there are two such words: “cats” and “and”.

“cats” appears in the files: brief1.txt, brief3.txt, brief4.txt

“and” appears in the files: brief1.txt, brief3.txt, brief4.txt

最佳答案

如果未找到键,则放置一个新的 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);
        }
    }
}

关于java - 使用 HashMap(String, ArrayList<String>),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33899232/

相关文章:

java - 计算两个日期之间的小时数,不包括周末

java - 计算多维数组中的字符数,Java

java - 可以为可卸载的动态编译代码获得 native 性能吗?

Java 线程错误 IllegalThreadState 线程已经启动

java - 如何在 Java 中创建包含 Javascript 代码的 JSONArray?

java - 如何通过Hibernate向mysql表添加数据(一对多)

java - 如何测试远程系统是否可达

java - 字 rune 字中转义数字的 Java 语义是什么,例如 '\15' ?

java - Spring MVC - 参数绑定(bind)

Java与mysql通信