Ste*_*n D 0 java hash hashmap map
我正在尝试打印我的地图以显示每个打印语句的键和值.我有重复的键和重复的值.例如:
key -> value
house -> dog
house -> cat
dog -> house
dog -> cat
cat -> house
cat -> bike
Run Code Online (Sandbox Code Playgroud)
这是我的文本文件:
house cat
house dog
house index
cat bike
cat house
cat index
dog house
dog cat
dog index
Run Code Online (Sandbox Code Playgroud)
出于某种原因,我的代码是打印字符串"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());
Run Code Online (Sandbox Code Playgroud)
我的代码中的简单print语句的输出如下所示:
index cat
index house
index dog
Run Code Online (Sandbox Code Playgroud)
如何将这些值添加到数据结构中以保持上面的密钥对?我怎样才能得到输出?:
house cat
house dog
house index
cat bike
cat house
cat index
dog house
dog cat
dog index
Run Code Online (Sandbox Code Playgroud)
我有重复的键和重复的值.
不,你没有.不在Map<K,V>.根据定义,键是唯一的.
但是,如果您提供的代码实际上是为每个值打印"索引",那么我强烈怀疑地图是不正确的,并且您的填充代码中有一个错误(我们看不到) .(或者,或者你使用一些自定义类作为值,它的toString方法总是返回"index".)
你应该退一步看看你的人口代码.
编辑:我修改了你的示例代码,以便编译,以便:
import java.io.*;
import java.util.*;
public class Test {
public static void main(String[] args) throws IOException {
Map<String, String> animals = new HashMap<String, String>();
BufferedReader in = new BufferedReader
(new InputStreamReader(new FileInputStream("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]);
}
for(Map.Entry entry : animals.entrySet())
System.out.println(entry.getValue() + " " + entry.getKey());
}
}
Run Code Online (Sandbox Code Playgroud)
并且使用animals.txt:
key1 value1
key2 value2
key3 value3
key4 value4
Run Code Online (Sandbox Code Playgroud)
输出是:
value4 key4
value3 key3
value2 key2
value1 key1
Run Code Online (Sandbox Code Playgroud)
根本没有"索引"的迹象.所以这不是你真正的人口代码(除了编译错误),或者你的文本文件对每个值都有"索引"......
| 归档时间: |
|
| 查看次数: |
377 次 |
| 最近记录: |