2015-11-24 137 views
0

我試圖讓程序讀取四個.txt文件並計算這些文件中的單詞。使用HashMap(String,ArrayList <String>)

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」中的「如果」。 基本上,我想我的輸出是這樣的:

文件的最大數目字出現在爲3,有兩個這樣的話:「貓」與「和」。

「貓」出現在文件:brief1.txt,brief3.txt,brief4.txt

「和」出現在文件:brief1.txt,brief3.txt,brief4.txt

+3

這個功課? –

+1

不,我希望我能在學校時學習java:( – Ravers

+1

)您可以使用'mapWords.containsKey'而不是'mapWords.keySet()。contains' –

回答

3

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

考慮使用番石榴MultiMap,這樣你就不必擔心檢查空ArrayList和維護。現在你只有兩行代碼要寫

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