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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。