gpt4 book ai didi

java - Hashmap 会覆盖值。如何添加多个相同的 key ?

转载 作者:行者123 更新时间:2023-12-01 17:53:28 25 4
gpt4 key购买 nike

我知道 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 的任何转换。 .

关于java - Hashmap 会覆盖值。如何添加多个相同的 key ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60759598/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com