hashmap

hashmap中merge的用法是什么

小亿
107
2024-04-18 18:35:12
栏目: 编程语言

在Java中,HashMap的merge()方法用于将指定的键和值合并到HashMap中。如果指定的键已经存在于HashMap中,则将当前键对应的值替换为指定值(使用提供的合并函数)。如果指定的键不存在于HashMap中,则将指定的键和值添加到HashMap中。

merge()方法的语法如下:

public V merge(K key, V value, BiFunction<? super V,? super V,? extends V> remappingFunction)

参数说明:

示例:

HashMap<Integer, String> map = new HashMap<>();
map.put(1, "Hello");

map.merge(1, "World", (value1, value2) -> value1 + " " + value2);

在上面的示例中,如果键1已经存在于HashMap中,则执行merge操作,将现有值"Hello"和新值"World"合并为"Hello World"。如果键1不存在于HashMap中,则直接将"World"作为值插入HashMap。

0
看了该问题的人还看了