I was trying to read a .txt file and wanted to store it in a hasmap(String, List). But when it tried to store the values were overwritten with the last value.
String filePath = "D:/liwc_new.txt";
HashMap<String,List<String>> map = new HashMap<String,List<String>>();
String line;
BufferedReader reader = new BufferedReader(new FileReader(filePath));
String key = null;
List<String> value = new ArrayList<String>();
//putting words in key and cat strings in value of map
int count = 0;
String cats[]= null;
value.clear();
while ((line = reader.readLine()) != null)
{
String[] parts = line.split(":", 2);
value.clear();
count++;
key = parts[0].trim();
cats=parts[1].split(", ");
for(int i=0;i<cats.length;i++) {
cats[i]=cats[i].trim();
cats[i]=cats[i].replace("[", "");
cats[i]=cats[i].replace("]", "");
value.add(cats[i]);
}
map.put(key, value);
//map.put(key, value);
}
The line List<String> value = new ArrayList<String>();
should be moved to the first line of your while loop and both calls to clear
removed.
The reason they are getting overwritten is you only ever allocate one list and put it in every value of the k:v pair of the map. So for every category, you have the same list, and the contents of that list are cleared and rebuilt every time a new line is read. So every value will have the contents of whatever was added after the last clear
.
On the other hand, if you create a new list with each iteration, each category will have it's own list, what you want.