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}
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}
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}
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}
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);
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使用;