Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial

Derek Derek
8,744 PointsJava WordCount
Hello, I am trying to write a WordCount program using java Hashmap. I think I am almost there, but I keep getting an error in my hashmap.get(key) method.. I really appreciate your help!
import java.util.HashMap;
public class MapReduce {
public static void main(String[] args) {
count("to be or not to be");
}
public static void count(String sentence) {
String[] words = sentence.split("(?=[,.])|\\s+");
HashMap<String, Integer> hashmap = new HashMap<String, Integer>();
for (String word : words) {
if (hashmap.containsKey(word)) {
hashmap.get(word) += 1;
} else {
hashmap.put(word, 1);
}
}
System.out.println(hashmap.entrySet());
}
}
Error message:
/Users/HyunJaeCho/Desktop/MapReduce.java:16: error: unexpected type hashmap.get(word) += 1; ^ required: variable found: value 1 error [Finished in 0.7s with exit code 1]
2 Answers

Tatenda Mushayakarara
2,447 Pointspublic static void count(String sentence) {
String[] words = sentence.split("(?=[,.])|\\s+");
HashMap<String, Integer> hashmap = new HashMap<>();
for (String word : words) {
if (hashmap.containsKey(word)) {
hashmap.get(word + 1);
} else {
hashmap.put(word, 1);
}
you should put the "+ 1 "inside the parenthesis. I hope it is clear. i cant find my words

Tatenda Mushayakarara
2,447 Pointshi.. I tried that piece of code over eclipse and it ran. Can you ask the question again this time with a link to show which challenge it was and I will take a look into it. Thanks!
Derek Derek
8,744 PointsDerek Derek
8,744 PointsHi, Tatenda, thank you for your help.
I don't think it is right though.. I am getting wrong results.. Also, it is not clear to me how you can add 1 to word which is a String..