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

标签 java

我知道 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/

相关文章:

java - 优化字符串操作代码

java - java编译中未经检查或不安全的操作错误?

java - 如何从另一个 java Activity 中播放声音?

java - 扩展对象与实现接口(interface)

java - 使用 java 8 Streams 对项目列表进行分组,并使用第一个项目而不是列表填充生成的 map

java - 如何编写 hql 查询以从逗号分隔的单词中搜索一个单词

java - 需要帮助理解 logcat 消息 ClassCastException

java - 与 JUNIT5 一起使用时 JMockit 库中出现异常

java - ActionListener 中的 setProperty

java - Arraylist 中的 ArrayList 移除方法行为