Reputation: 115
I have a problem with my Java Code. I want to store multiple Values in one Key but I want to store them flexible. This means I read from a textfile and every line is one word. To store them, I want to build pairs of words. For example:
word1/word2
word2/word3
word3/word4
I have changed this method a little bit. I want to store the values of the keys in an arraylist. This means everytime when a new key comes up a new Arraylist and key will be stored, but if the key is in the map I want to store them in the list of this key. Is this possible?
We have to store them in a hashmap. But I can not get it to work:
private HashMap<String, ArrayList<String>> hmap = new HashMap<String, ArrayList<String>>();
private ArrayList<String> wort2;
public GrammelotH(String filename) throws IOException {
String fixWort = ".";
BufferedReader br = new BufferedReader(new FileReader(filename));
while (br.ready()) {
String line = br.readLine();
if (hmap.containsKey(fixWort)) {
hmap.put(fixWort, wort2.add(line));
}else {
hmap.put(fixWort, new ArrayList<String>().add(line));
}
fixWort = line;
}
br.close();
}
The problem is the put order. Has anybody of you an idea how to get
hmap.put(fixWort, new ArrayList<String>().add(line));
and
hmap.put(fixWort, wort2.add(line));
to work?
Thank you for your help! Bye Bye!
Upvotes: 0
Views: 92
Reputation: 7335
I think I'd be looking at something like
List l = hmap.get(line);
if (l != null) {
l.add(line));
}else {
l = new ArrayList<String>();
l.add(line)
hmap.put(line, l);
}
So, you see if the map already contains the line
you have just read from the file. If it does, you just add it to the associated list. If it doesn's.create a list, add line
to it, and then add both to the Map.
Upvotes: 1