c.timothy
c.timothy

Reputation: 97

HashMap String occurrences in a file [JAVA]

I'm learning about HashMaps in my Java course and I got given a task to store all the words from a text file in a HashMap and print out each unique words and the amount of occurrences of it in the file.

I couldn't figure out how to do this so searched for help here and found this link: Using HashMap to count instances

I adapted and used the Posters code into my program and it worked but I don't fully understand why and I don't want to give in something I don't understand that I didn't do myself.

I've posted my full code below but could someone please explain to me how the commented on sections function.

   public class Q3HM {
   public static void main(String[] args) {
        HashMap<String, Integer> map = new HashMap<String, Integer>(50, 10);
                               *****//Not sure what the (50,10) is for

        try {
            File input = new File("input.txt");
            Scanner read = new Scanner(new FileInputStream(input));
            ArrayList<String> list = new ArrayList<>();

            while (read.hasNext()) {
                list.add(read.next());
            }

   *******//Not sure how the below for loop works
            for (String w : list){ 
                Integer i = map.get(w);
                if(i == null){
                    map.put(w, 1);
                }
                else {
                    map.put(w, i+1);
                }
            }
   *******//End of section I'm confused about

            System.out.println(map.toString());
        }
        catch (Exception e){
            e.printStackTrace();
        }
    }
}

Upvotes: 0

Views: 2301

Answers (3)

Salem
Salem

Reputation: 14917

for (String w : list) {
    Integer i = map.get(w);
    if(i == null) {
        map.put(w, 1);
    }
    else {
        map.put(w, i+1);
    }
}

For every string in the list,
      Get the old value and store it as i.
      IF the string is not yet in the map (i is null), insert 1. (First occurrence)
      OTHERWISE, insert (i + 1) (Add one to the current count.)

A more descriptive rewrite could be

for (String word : list) {                 //For every word in list,
    Integer previousAmount = map.get(word);    //Get the current count and store it.
    if(previousAmount == null)             //If the count doesn't exist (null, not in map),
        map.put(word, 1);                  //Put 1 in the map (first time.)
    else                                   //Otherwise (in the map)
        map.put(word, previousAmount + 1); //Add one to the current amount
}

This also could have simply been written as

for(String w : list)
    map.put(w, map.getOrDefault(w, 0) + 1);

Upvotes: 3

OldCurmudgeon
OldCurmudgeon

Reputation: 65811

I find clear comments help a lot.

    // For each word in the list.
    for (String w : list) {
        // Get it's current count from the Map.
        Integer i = map.get(w);
        if (i == null) {
            // Null means never seen before so it's count becomes 1
            map.put(w, 1);
        } else {
            // Seen this word - add one to the count.
            map.put(w, i + 1);
        }
    }

Upvotes: 1

Urko Pineda
Urko Pineda

Reputation: 132

for (String w : list){
  Integer i = map.get(w);
  if(i == null){
    map.put(w, 1);
  }
  else {
    map.put(w, i+1);
  }
}

If the string (w) is in the HashMap (map.get(w)), then the new string is introduced in the HashMap; otherwise, the string is introduced (again) and the counter is modified (i+1)

Upvotes: 1

Related Questions