<>HashMap的带函数参数方法



文章目录

* HashMap的带函数参数方法
<https://blog.csdn.net/tangzekk/article/details/89739255#HashMap_0>
* 1. 如果key没有value,或者连key都没有 就怎么怎么滴 computeIfAbsent()
<https://blog.csdn.net/tangzekk/article/details/89739255#1_keyvaluekey__computeIfAbsent_3>
* 2. 如果存在key有value就怎么怎么滴 computeIfPresent()
<https://blog.csdn.net/tangzekk/article/details/89739255#2_keyvalue_computeIfPresent_21>
* 3. 针对某个key 怎么怎么滴 compute()
<https://blog.csdn.net/tangzekk/article/details/89739255#3_key__compute_38>
* 4. key如果无value 给值,有value 函数覆盖 merge()
<https://blog.csdn.net/tangzekk/article/details/89739255#4_keyvalue_value__merge_57>
* 5. 遍历 没说的 forEach()
<https://blog.csdn.net/tangzekk/article/details/89739255#5___forEach_70>
* 6. 监视所有key 替换 replaceAll()
<https://blog.csdn.net/tangzekk/article/details/89739255#6_key__replaceAll_86>
* 其他 <https://blog.csdn.net/tangzekk/article/details/89739255#_106>


<>1. 如果key没有value,或者连key都没有 就怎么怎么滴 computeIfAbsent()
Map map = new HashMap(); map.put(0, null); map.put(1, "a"); map.put(2, "b");
map.put(3, "c"); map.computeIfAbsent(0,(x)->{ if (System.currentTimeMillis() % 2
==0) { return "整除2"; } return "不能整除2"; }); System.out.println(map); // {0=整除2,
1=a, 2=b, 3=c}
<>2. 如果存在key有value就怎么怎么滴 computeIfPresent()
Map<Integer,String> map = new HashMap(); map.put(0, null); map.put(1, "a");
map.put(2, "b"); map.put(3, "c"); map.computeIfPresent(2,(x,y)->{ if (x % 2 == 0
) { return "不为空,且取余 2 = 0"; } return "不为空,且取余2 != 0"; }); System.out.println(map
); // {0=null, 1=a, 2=不为空,且取余 2 = 0, 3=c}
<>3. 针对某个key 怎么怎么滴 compute()
Map<Integer,String> map = new HashMap(); map.put(0, null); map.put(1, "a");
map.put(2, "b"); map.put(3, "c"); map.compute(4,(k,v)->{ if (v == null) { return
"yes null"; } return "no null"; }); System.out.println(map); // {0=null, 1=a,
2=b, 3=c, 4=yes null}
<>4. key如果无value 给值,有value 函数覆盖 merge()
Map<Integer,String> map = new HashMap(); map.put(0, null); map.put(1, "a");
map.put(2, "b"); map.put(3, "c"); // key has value?"填补空缺":"覆盖原值" map.merge(1,
"填补空缺",(k,v)-> "覆盖原值"); System.out.println(map); // {0=null, 1=覆盖原值, 2=b, 3=c}
<>5. 遍历 没说的 forEach()
List list=new ArrayList(); Map<Integer,String> map = new HashMap(); map.put(0,
null); map.put(1, "a"); map.put(2, "b"); map.put(3, "c"); map.forEach((k,v)->{
list.add(k); list.add(v); }); System.out.println(list);
<>6. 监视所有key 替换 replaceAll()
Map<Integer,String> map = new HashMap(); map.put(0, null); map.put(1, "a");
map.put(2, "b"); map.put(3, "c"); map.replaceAll((k,v)->{ if (k == 1) { return
"一"; } else if (v == null) { return "本来是空"; } return "懒得写了,其他情况"; }); System.out
.println(map); // {0=本来是空, 1=一, 2=懒得写了,其他情况, 3=懒得写了,其他情况}
<>其他

有点提一下
map.values(); 返回的事Collection类型,不知道啥情况.可以new ArrayList(Collection);转List使用;

友情链接
ioDraw流程图
API参考文档
OK工具箱
云服务器优惠
阿里云优惠券
腾讯云优惠券
华为云优惠券
站点信息
问题反馈
邮箱:ixiaoyang8@qq.com
QQ群:637538335
关注微信