我正在尝试打印我的地图以显示每个打印语句的键和值。我有重复的键和重复的值。例如:
key -> value
house -> dog
house -> cat
dog -> house
dog -> cat
cat -> house
cat -> bike
这是我的文本文件:
house cat
house dog
house index
cat bike
cat house
cat index
dog house
dog cat
dog index
出于某种原因,我的代码正在打印字符串“索引”而不是实际值。我的代码在这里:
//adding values from a text file of two words per line.
//those two words per line in the text file are tab delimitted
public static Map<String, String> animals = new HashMap<String, String>();
BufferedReader in = new BufferedReader(new InputStreamReader("animals.txt"));
String current_line;
String[] splitted_strings = new String[1];
while ((current_line = in.readLine()) != null){
splitted_strings = current_line.split("\t");
animals.put(splitted_strings[0], splitted_strings[1]);
}
//print statement
for(Map.Entry entry : animals.entrySet())
System.out.println(entry.getValue() + " " + entry.getKey());
下面显示的代码中的简单打印语句的输出如下所示:
index cat
index house
index dog
如何将这些值添加到数据结构中以保留上述密钥对?我怎样才能得到这样的输出?:
house cat
house dog
house index
cat bike
cat house
cat index
dog house
dog cat
dog index