HashMap的带函数参数方法
文章目录
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使用;