简体   繁体   English

如何从结果集中创建多个键值哈希图

[英]How to create multiple key value hashmaps from a resultset

I would like to create multiple hashmaps from a resultset. 我想从一个结果集中创建多个哈希图。

The final result should be something like below; 最终结果应如下所示;

{
  slot_name = recommend,
  data = 7,
},
{
  slot_name = service,
  data = Good,
},
{
  slot_name = staff,
  data = Great,
},

I tried as below: 我尝试如下:

HashMap<String, String> data = new HashMap<String, String>();

while (resultSet.next()) {
    data.put("slot_name", resultSet.getString("name"));
    data.put("data", resultSet.getString("param_value"));
}

But when I printout the value of the hashmap, I get one record as below System.out.println(data); 但是当我打印出哈希图的值时,我得到了一条记录,如下所示: System.out.println(data);

{
  slot_name = staff,
  data = Great,
}

How can I achieve this? 我该如何实现? Someone assist, thank you 有人协助,谢谢

I would recommend to have a list and create a model class(instead of HashMaps) for "slot_name" and "data". 我建议有一个列表,并为“ slot_name”和“ data”创建一个模型类(而不是HashMaps)。 Inside loop, construct object and add to the list. 在循环内部,构造对象并添加到列表中。 The reason, you are not getting as expected, is because, HashMap will have unique keys. 之所以不能如预期那样,是因为HashMap将具有唯一的键。 So, for the same key when the value is again added, it will get updated. 因此,对于再次添加该值的同一键,它将被更新。

class YourModel {
    String slotName;
    String data;
}

// inside loop
list.add(new YourModel(resultSet.getString("name"), resultSet.getString("param_value"));

A HashMap is a key value store. HashMap是键值存储。 If you put the same key more than once, previous will be overwritten. 如果您多次输入相同的密钥,则先前的密钥将被覆盖。 This is the reason you saw only the last entry in the output. 这就是您仅在输出中看到最后一个条目的原因。

if you want multiple maps, well create multiple ones. 如果您想要多个地图,请创建多个地图。 Eg., 例如。,

List<HashMap<String,String> maps = new ArrayList();
while (resultSet.next()) {
    HashMap<String, String> data = new HashMap<String, String>();
    data.put("slot_name", resultSet.getString("name"));
    data.put("data", resultSet.getString("param_value"));
    maps.add(data);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM