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