[英]How to combine two HashMaps only if key not present?
我正在用Java組合兩個HashMap。 我不希望hs2
值覆蓋的值hs1
,我想只有當不存在相結合。
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.stream.Collectors;
import java.util.HashMap;
public class Test {
public static void main(String args[]) {
HashMap<Object,String> hs1 = new HashMap<>();
hs1.put(1, "ram");
hs1.put(2, "sita");
HashMap<Object,String> hs2 = new HashMap<>();
hs2.put(2, "test");
hs2.put(5, "fre");
HashMap<Object,String> hs3 = new HashMap<>() ;//Map is which we add
hs3.putAll(hs1);
hs3.putAll(hs2);
System.out.println(" hs3 : " + hs3);
}
}
預期結果 :
{1 = ram,5 = fre,2 = sita}
我不希望hs2覆蓋僅要在不存在的情況下合並的hs1的值
在這種情況下, hs2
添加hs2
的條目,然后添加hs1
的條目:
HashMap<Object,String> hs3 = new HashMap<>(hs2);
hs3.putAll(hs1);
我認為最簡單的方法是:
hs2.forEach(hs1::putIfAbsent);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.