java - Hashmap 覆盖值。如何添加多个相同的密钥?
问题描述
我知道 hashMap 会覆盖 kay,但我确实需要为另一个值提供相同的键。还有一个问题是,在 postRequest 再往下,它需要设置为一个Map
值。
那么如何修复下面的内容,以便正文包含所有字段及其值,如下表所示?
所以我们不能有field3 = tree, cone
,它必须是字段3 = tree, field 3 = cone
,否则服务将失败。
Example step:
|field |value |
|----------|--------------------------------------------|
|field1 |shop |
|field2 |apple |
|field3 |tree |
|field3 |cone |
@Step("Example step: <table>")
public void exampleStep(Table table) {
Map<String, Object> body = new HashMap<>();
table.getTableRows().forEach(row -> {
String value = row.getCell(VALUE);
String field = row.getCell(FIELD);
body.put(field, value);
});
final String url = String.format("%s/service/%s", System.getenv(ENDPOINT), service);
new DBrequest(dataStore, url, HttpMethod.POST).postRequest(body);
解决方案
例如,如果您有一个Map<String, List<String>>
示例,则必须在输入值时检查键是否存在,请参见:
@Step("Example step: <table>")
public void exampleStep(Table table) {
table.getTableRows().forEach(row -> {
String value = row.getCell(VALUE);
String field = row.getCell(FIELD);
// you have to check if the key is already present
if (body.containsKey(field)) {
// if it is, you can simply add the new value to the present ones
body.get(field).add(value);
} else {
// otherwise you have to create a new list
List<String> values = new ArrayList<>();
// add the value to it
values.add(value);
// and then add the list of values along with the key to the map
body.put(field, values);
}
});
}
您可以通过多种方式迭代这样的Map
,一种是:
for (Entry<String, List<String>> entry : body.entrySet()) {
// print the key first
System.out.println(entry.getKey() + ":");
// then iterate the value (which is a list)
for (String value : entry.getValue()) {
// and print each value of that list
System.out.println("\t" + value);
}
};
}
请注意:
这是一个没有任何内容的简单示例,它不处理来自Object
.
推荐阅读
- python - Spyder(Anaconda)在强制关闭后无法启动
- optimization - 如何在 MiniZinc 中提高我的图形着色模型的性能?
- google-maps - 执行步骤后 Google Maps API 不显示地图
- javascript - 为什么使用 if 语句通过在输入上调用函数不会使值变为 false?
- r - 使用逗号分隔的字符串为每一行绘制一组值
- c++ - 如何根据两个因素组织向量:id 和数量?(C++)
- html - 粘性 div 占据所有宽度
- python - ValueError:logits 和标签必须具有相同的形状 ((None, 10) vs (None, 12))
- ssh - 来自共享 Gitlab 运行器的 SSH 停止工作
- reactjs - React useEffect 和 React-Router - 当用户导航到新页面时,在组件中重新发送 API 调用