How to get a single value from a Map?
My problem starts off by reading this text file in:
Every good boy does fine and
the quick brown fox jumps over the lazy dog and
We have to create a map and use each word as a key and what # the word is as the value. This is what should be printed out:
Every 1, (Every is the first word, so it has a 1, next to it)
and 6,16, (and is used twice as the 6th and 16th word, so it has 6, and 16,)
boy 3,
I have to use a HashMap<String, StringBuilder> to store the values, and I have no problems up to using the put(K,V) method. However, I don't know how to add a second value, such as 16 for and in the example above.
Variables in my program:
indexMap is the hashMap, String word is the key, and StringBuilder sb is the value.
I can do indexMap.put(word, sb); to add it to the Map but when I do that, the key and value are replaced. I need the new value to be appended to the end of the current value. My plan was to get the value already stored, append it to the StringBuilder, and then append the new value I want to add to the end of that. The problem I'm having is in getting that single value that is in the Map, so basically I don't know how to get "6," when I want to add "16," to the end of it.
This is what I wanted to do in code, except that getValue() doesn't work:
//if the key already exists
if(indexMap.containsKey(word))
{
//get the value in the word and append it to the StringBuilder
sb.append(indexMap.getValue(word) + ",");
//get the new value to add and append it to the end of StringBuilder
sb.append((Integer.toString(count) + ",");
//clear the existing key and map
indexMap.remove(word);
//put the key and the new value in
indexMap.put(word, sb);
}
The core problem is how to append what numbered word it is to the current value in the spot, so if what I thought is completely off, I would appreciate if someone told me the right way to go about doing it =p. Thank you very much.