0

I am trying to make the program read four .txt files and count the words in those files.

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". 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” appears in the files: brief1.txt, brief3.txt, brief4.txt

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

2
  • 1
    No, I wish i could learn java when I was at school :( Commented Nov 24, 2015 at 16:49
  • 1
    You can use mapWords.containsKey instead of mapWords.keySet().contains Commented Nov 24, 2015 at 16:54

2 Answers 2

3

put a new ArrayList if the key was not found. Afterwards use the 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);
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

Consider using a Guava MultiMap so that you don't have to worry about checking for the null ArrayList and maintenance. 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());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.