java - Java Map 键的奇怪输出

标签 java hash dictionary hashmap

我正在尝试打印我的 map 以显示每个打印语句的键和值。我有重复的键和重复的值。例如:

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

由于某种原因,我的代码打印字符串“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

如何将这些值添加到数据结构中以保留如上所述的 key 对? 我怎样才能得到这样的输出?:

house cat
house dog
house index
cat bike
cat house
cat index
dog house
dog cat
dog index

最佳答案

I have duplicate keys and duplicate values.

不,你不知道。不在Map<K,V>中。根据定义,键是唯一的。

如果您想要每个键有多个值,则需要类似 Guava 的内容的 Multimap .

但是,如果您提供的代码确实为每个值打印“索引”,那么我强烈怀疑 map 一开始就是不正确的,并且您的人口代码中有一个错误(我们可以'没看到)。 (要么,或者您使用某些自定义类作为值,并且其 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());
    }
}

动物.txt 为:

key1    value1
key2    value2
key3    value3
key4    value4

输出是:

value4 key4
value3 key3
value2 key2
value1 key1

根本没有“索引”的迹象。因此,这要么不是您真正的人口代码(除了编译错误),要么您的文本文件的每个值都有“索引”...

关于java - Java Map 键的奇怪输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15260993/

相关文章:

java - 小挑战。比较 3 个单独数组的总和

java - Maven编译错误-包不存在

java - 我想使用 HttpClient4 对并发发送请求进行 RESTful API 压力测试,我可以使用一个 HttpClient 实例吗?

c++ - 创建更好的哈希函数

javascript - JavaScript 变量引用数组的问题

java - 在 Java 中修改 final 字段

hashtable - 分析目标并选择良好的哈希函数

algorithm - MD5哈希函数

python - 两个字典的合并和求和

python - 用字典扩展数据框