簡體   English   中英

使用HashMap(String,ArrayList <String> )

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

我試圖使程序讀取四個.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”。 基本上,我希望我的輸出是這樣的:

一個單詞出現的最大文件數是三個,並且有兩個這樣的單詞:“ cats”和“ and”。

“ cats”出現在文件中:brief1.txt,brief3.txt,brief4.txt

“ and”出現在文件中:brief1.txt,brief3.txt,brief4.txt

如果找不到密鑰,則放置一個新的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);
        }
    }
}

考慮使用Guava MultiMap,這樣您就不必擔心檢查空ArrayList和維護。 現在您只需要編寫兩行代碼

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