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