[英]How to add using HashMap multiple values(different types, an int and a string) with the same key?
[英]Hashmap overwrites values. How to add multiple of the same key?
我知道 hashMap 会覆盖 kay,但我确实需要为另一个值提供相同的键。 还有一个问题是,在进一步向下的 postRequest 中,需要将其设置为Map
值。
那么如何修复下面的内容,以便正文包含表中显示的所有字段及其下面的值?
所以我们不能有field3 = tree, cone
,它必须是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
任何转换。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.