Search code examples
arraysarraylisthashmap

Adding a value from an ArrayList to a HashMap


Based off of this text file: 4 a excellent movie 0 a bad movie 3 pretty decent movie

I'm suppose to get the amount of times a word appears and each word in the line has a "score" based off of the number at the beginning of the line (a=4, excellent=4, movie=4).

My code needs to print two HashMaps<String, Integer>: Word totals: {a=4, pretty=3, movie=7, bad=0, excellent=4, decent=3}

Word counts: {a=2, pretty=1, movie=3, bad=1, excellent=1, decent=1}

with my code so far I am able to print word counts but I am unsure how to do word totals. Any help would be appreciated. Thank You.

/**
 * Given an ArrayList of review Strings, compute the total score associated with
 * each word and the number of times each word appears.
 * 
 * @param reviews     An ArrayList of lines representing reviews. The first word
 *                    in each line is a score.
 * @param totalScores a HashMap of each word as a key and its total score as the
 *                    value
 * @param wordCount   a HashMap of each word as a key and the number of times it
 *                    appears in the reviews as a value
 */
public void computeScoreAndCounts(ArrayList<String> reviews, HashMap<String, Integer> totalScores,
        HashMap<String, Integer> wordCount) {
    for (String line : reviews) {
        String[] items = line.split(" ");
        int reviewScore = Integer.parseInt(items[0]);
        String noScore = "";
        for (int index2 = 1; index2 < items.length; index2++) {
            noScore = items[index2] + " ";
            String[] items2 = noScore.split(" ");
            for (String word : items2) {
                if (wordCount.containsKey(word)) {
                    int currentCount = wordCount.get(word) + 1;
                    wordCount.put(word, currentCount);
                } else {
                    wordCount.put(word, 1);
                }
            }
            for (String word : items2) {
                if (!totalScores.containsKey(word)) {
                    totalScores.put(word, reviewScore);
                } else {
                    int totalScore = totalScores.get(word);
                    totalScores.put(word, totalScore + 1);
                }
                    
            }
        }
    }
    // Loop over all the reviews.
    // Break a review into words with String split.
    // Find the score for the review using the first item in the split array and
    // Integer.parseInt.
    // Loop over the rest of the words.
    // For each word, build up the score and total HashMap entries.

    
    System.out.println("Word totals: " + totalScores);
    System.out.println("Word counts: " + wordCount);

}

Solution

  • import java.util.regex.*;
    import java.util.HashMap;
    public class Program
    {
        public static void main(String[] args) {
    
            String file = "4 a excellent movie 0 a bad movie 3 pretty decent movie";
            
            String[] scores = file.split("(?=[0-9])");
            
            HashMap<String,Integer> wordTotals = new HashMap();
            
            for (String s: scores) {
                System.out.println(s);
                String numberString = s.replaceAll("[^0-9]+","");
                Integer number = Integer.parseInt(numberString);
                String lineWithoutNumber = s.replaceAll("[0-9]","");
                System.out.println("number:"+number);
                System.out.println("line without number:"+lineWithoutNumber);
                
                String[] words = lineWithoutNumber.trim().split(" ");
                for (String word : words) {
                    System.out.println("word:"+word);
                    if (!wordTotals.containsKey(word)) {
                        wordTotals.put(word,0);
                    }
                    wordTotals.put(word, wordTotals.get(word) + number);
                }
                
            }
            
            System.out.println(wordTotals);
            
        }
    }
    

    This would be the result:

    4 a excellent movie 
    number:4
    line without number: a excellent movie 
    word:a
    word:excellent
    word:movie
    0 a bad movie 
    number:0
    line without number: a bad movie 
    word:a
    word:bad
    word:movie
    3 pretty decent movie
    number:3
    line without number: pretty decent movie
    word:pretty
    word:decent
    word:movie
    {a=4, pretty=3, movie=7, bad=0, excellent=4, decent=3}