[英]Java HashMap multiple keys with multiple values assigned flexible
I have a problem with my Java Code. 我的Java代码有问题。 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 单词1 /单词2
word2/word3 单词2 /单词3
word3/word4 word3 / word4
I have changed this method a little bit. 我已经稍微改变了这种方法。 I want to store the values of the keys in an arraylist.
我想将键的值存储在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.
这意味着每次出现新密钥时,都会存储一个新的Arraylist,并且将存储该密钥,但是如果该密钥在映射中,我希望将其存储在此密钥的列表中。 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!
再见!
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. 因此,您可以查看地图是否已经包含刚从文件中读取的
line
。 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. 如果没有,请创建一个列表,在其中添加
line
,然后将两者都添加到地图中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.