使用循环将数据添加到HashMap中

时间:2015-07-18 13:49:20

标签: java hadoop mapreduce

我正在尝试将从序列文件中读取的数据放入Hash Map中。循环结束后,我尝试打印出错的内容。

我试图在第一个循环中打印键和值,结果是正确的。当我尝试在第二个while循环中打印密钥时,结果是几个重复的记录。我无法弄清楚出了什么问题。

    while(reader.next(key, value)) {
        byte[] value_bytes = value.getBytes();
        data_HashMap.put(key, value_bytes);
    }

    IOUtils.closeStream(reader);

    Iterator<Text> keySetIterator = data_HashMap.keySet().iterator();
    while(keySetIterator.hasNext()){
      Text index = keySetIterator.next();
      System.out.println("key: " + index);
    }

这是结果

Key: 123
Key: 123
Key: 123
Key: 123
Key: 123
Key: 123

如果我像这样修改了第一个while循环

while(reader.next(key, value)) {
    byte[] value_bytes = value.getBytes();
    System.out.println("Key: " + key);
}

这是结果,这是正确的。

Key: 123
Key: 456
Key: 789
Key: 741
Key: 852
Key: 963

1 个答案:

答案 0 :(得分:2)

您将重新使用相同的密钥:

while(reader.next(key, value)) {
    byte[] value_bytes = value.getBytes();
    data_HashMap.put(**key**, value_bytes);
}

我不知道类型是什么,但如果它是Text,只需复制它或使用String代替。

while(reader.next(key, value)) {
    byte[] value_bytes = value.getBytes();
    data_HashMap.put(key.toString(), value_bytes);
}

你也会遇到与值字节相同的问题,所以我建议你也要对这个数组做一个防御性的副本。