首页 > 解决方案 > 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);

标签: java

解决方案


例如,如果您有一个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.


推荐阅读