ConcurrentHashMap 类合并集的 merge() 方法如果指定的键尚未与(非空)值相关联,则将其与给定值相关联。
用法
public V merge(K key, V value, BiFunction<? super V,? super V,? extends V> remappingFunction)
参数
key - 与指定值关联的键
value - 如果不存在则使用的值
remappingFunction - 重新计算值(如果存在)的函数
返回
与指定键关联的新值,如果没有,则为 null
抛出
不会抛出异常。
例子1
import java.util.*;
import java.util.concurrent.*;
public class ConcurrentHashMapmergeExample1 {
public static void main(String[] args)
{
ConcurrentHashMap<Integer, String> conmap = new ConcurrentHashMap<Integer, String>();
conmap.put(1, "Java");
conmap.put(2, "php");
conmap.put(3, ".net");
conmap.put(5, "python");
ConcurrentHashMap<Integer, String> conmap2 = new ConcurrentHashMap<Integer, String>();
conmap2.put(1, "C");
conmap2.put(2, "C++");
conmap2.put(3, "Rubi");
conmap2.put(5, "Java Script");
conmap2.forEach(
(key, value) -> conmap.merge( key, value, (v1, v2) -> v1.equalsIgnoreCase(v2) ? v1:v1 + "," + v2)
);
System.out.println(conmap);
}
}
输出:
{1=Java,C, 2=php,C++, 3=.net,Rubi, 5=python,Java Script}
例子2
import java.util.*;
import java.util.concurrent.*;
public class ConcurrentHashMapmergeExample2 {
public static void main(String[] args)
{
ConcurrentHashMap<Integer, String> conmap = new ConcurrentHashMap<Integer, String>();
conmap.put(1, "A");
conmap.put(2, "B");
conmap.put(3, "C");
conmap.put(5, "E");
ConcurrentHashMap<Integer, String> conmap2 = new ConcurrentHashMap<Integer, String>();
conmap2.put(1, "F");
conmap2.put(2, "G");
conmap2.put(3, "H");
conmap2.put(5, "I");
conmap2.forEach(
(key, value) -> conmap.merge( key, value, (v1, v2) -> v1.equalsIgnoreCase(v2) ? v1:v1 + "," + v2)
);
System.out.println(conmap);
}
}
输出:
{1=A,F, 2=B,G, 3=C,H, 5=E,I}
相关用法
- Java ConcurrentHashMap mappingCount()用法及代码示例
- Java ConcurrentHashMap contains()用法及代码示例
- Java ConcurrentHashMap newKeySet()用法及代码示例
- Java ConcurrentHashMap elements()用法及代码示例
- Java ConcurrentHashMap forEach()用法及代码示例
- Java ConcurrentHashMap putIfAbsent()用法及代码示例
- Java ConcurrentHashMap computeIfAbsent()用法及代码示例
- Java ConcurrentHashMap isEmpty()用法及代码示例
- Java ConcurrentHashMap equals()用法及代码示例
- Java ConcurrentHashMap putAll()用法及代码示例
- Java ConcurrentHashMap hashcode()用法及代码示例
- Java ConcurrentHashMap containsKey()用法及代码示例
- Java ConcurrentHashMap put()用法及代码示例
- Java ConcurrentHashMap computeIfPresent()用法及代码示例
- Java ConcurrentHashMap toString()用法及代码示例
- Java ConcurrentHashMap replace()用法及代码示例
- Java ConcurrentHashMap clear()用法及代码示例
- Java ConcurrentHashMap size()用法及代码示例
- Java ConcurrentHashMap remove()用法及代码示例
- Java ConcurrentHashMap keys()用法及代码示例
注:本文由纯净天空筛选整理自 Java ConcurrentHashMap merge() Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。