Map.merge()的使用

1.模拟数据

List<JSONObject> list=new ArrayList<>();
JSONObject object1=new JSONObject();
object1.put("name","张三");
object1.put("num",4);
list.add(object1);

JSONObject object2=new JSONObject();
object2.put("name","张三");
object2.put("num",6);
list.add(object2);

2.merge之合并

Map<String,Integer> map=new HashMap<>();
list.foreach(info-> map.merge(info.getString("name"),info.getInteger("num"),Integer::sum));
for(String s:map.keySet()){
   System.out.println(map.get(s));
}
--打印结果为:10

3.merge之覆盖

Map<String,Integer> map=new HashMap<>();
list.foreach(info-> map.merge(info.getString("name"),info.getInteger("num"),(oldV,newV)->newV));
for(String s:map.keySet()){
   System.out.println(map.get(s));
}
--打印结果为:6

4.merge之删除

Map<String,Integer> map=new HashMap<>();
list.foreach(info-> map.merge(info.getString("name"),info.getInteger("num"),(oldV,newV)->null));
for(String s:map.keySet()){
   System.out.println(map.get(s));
}
--无打印,且删除对应key

发表评论

电子邮件地址不会被公开。 必填项已用*标注

2 × 4 =