Ravers
Ravers

Reputation: 1040

Using HashMap(String, ArrayList<String>)

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

Upvotes: 0

Views: 130

Answers (2)

Amir Afghani
Amir Afghani

Reputation: 38511

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());

Upvotes: 0

J&#246;rn Buitink
J&#246;rn Buitink

Reputation: 2916

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);
        }
    }
}

Upvotes: 3

Related Questions