put与putIfAbsent区别:

put在放入数据时,如果放入数据的key已经存在与Map中,最后放入的数据会覆盖之前存在的数据,

而putIfAbsent在放入数据时,如果存在重复的key,那么putIfAbsent不会放入值。

putIfAbsent   如果传入key对应的value已经存在,就返回存在的value,不进行替换。如果不存在,就添加key和value,返回null

底层实现:

public V put(K key, V value) { if (value == null) throw new NullPointerException(); int hash = hash(key.hashCode()); return segmentFor(hash).put(key, hash, value, false);
}
public V putIfAbsent(K key, V value) { if (value == null) throw new NullPointerException(); int hash = hash(key.hashCode()); return segmentFor(hash).put(key, hash, value, true);
}

例子:

package com.xx;import java.util.HashMap;
import java.util.Map;/*** JustForTest** @create 2018-06-20 12:14*/
public class TestHan {public static void main(String[] args) {/*** put*/Map<Integer,String> map = new HashMap<>();map.put(1,"ZhangSan");map.put(2,"LiSi");map.put(1,"WangWu");map.forEach((key,value) ->{System.out.println("key : " + key + " , value : " + value);});/*** putIfAbsent*/Map<Integer,String> putIfAbsentMap = new HashMap<>();putIfAbsentMap.put(1,"张三");putIfAbsentMap.put(2,"李四");putIfAbsentMap.put(1,"王五");putIfAbsentMap.forEach((key,value) ->{System.out.println("key : " + key + " , value : " + value);});}
}

输出结果:

key : 1 , value : WangWu

key : 2 , value : LiSi

key : 1 , value : 张三

key : 2 , value : 李四

package com.xx;import com.alibaba.fastjson.JSON;import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;/*** JustForTest** @create 2018-06-20 12:14*/
public class TestHan {/*** 处理重复数据与不重复数据,以重复数据为唯一,合并数据的方法。*/public static void main(String[] args) {List<Student> list = new ArrayList<>();list.add(new Student("张三", 1));list.add(new Student("李四", 1));list.add(new Student("王五", 2));list.add(new Student("赵六", 1));list.add(new Student("孙七", 2));list.add(new Student("周八", 1));list.add(new Student("吴九", 2));//对于上面的学生、如果根据班级进行区分?!Map<Integer,List<Student>> map = new HashMap<>();List<Student> students;for(Student s : list) {/*** put不管什么直接存入,返回旧值* putIfAbsent如果为null才存入,返回旧值。*/students = map.putIfAbsent(s.getInClass(),new ArrayList<Student>(list.size()));if (null == students) {students = map.get(s.getInClass());}students.add(s);}//循环Mapmap.forEach((key,value) -> {System.out.println("班级:" + key + ",人员:" + JSON.toJSONString(value));});}}
package com.xx;/*** @author hanliwei* @create 2018-06-20 16:00*/
public class Student {private String name; //姓名private Integer inClass;//所属班级Student(String name,Integer inClass) {this.name = name;this.inClass = inClass;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Integer getInClass() {return inClass;}public void setInClass(Integer inClass) {this.inClass = inClass;}
}

------------------------------

Java8之Map的其他一些方法

------------------------------

Map<Integer,String> map = new HashMap<>();
map.put(1,"a");
map.put(2,"b");
map.put(3,"c");
/*** 1.getOrDefault 方法** 如果指定的key存在,则返回该key对应的value,* 如果不存在,则返回指定的值。** 例子:key为4不存在,输出d*/
System.out.println(map.getOrDefault(4,"d"));

输出:d

/*** 2.forEach 方法** 遍历Map中的所有Entry, 对key, value进行处理, 接收参数 (K, V) -> void,*/
map.forEach((key,value) -> System.out.println("key : " + key + " , value:" + value));

输出:

key : 1 , value:a

key : 2 , value:b

key : 3 , value:c

/*** 3.replaceAll 方法* 替换Map中所有Entry的value值,这个值由旧的key和value计算得出,接收参数 (K, V) -> V*/
map.replaceAll((key,value) -> ("new" + key) + value);
map.forEach((key,value) -> System.out.println("key : " + key + " , value:" + value));

输出:

key : 1 , value:new1a

key : 2 , value:new2b

key : 3 , value:new3c

/*** 4.putIfAbsent 方法* 如果key关联的value不存在,则关联新的value值,返回key关联的旧的值*/
map.putIfAbsent(3, "d");
map.putIfAbsent(4, "d");
System.out.println(map.get(3));
System.out.println(map.get(4));

输出:

c

d

/*** 5.remove方法* 接收2个参数,key和value,如果key关联的value值与指定的value值相等(equals),则删除这个元素*/
map.remove(1,"b");
System.out.println(map.get(1));
//未删除成功,输出amap.remove(2,"b");
System.out.println(map.get(2));
//删除成功,输出null
/*** 6.replace(K key, V oldValue, V newValue) 方法* 如果key关联的值与指定的oldValue的值相等,则替换成新的newValue*/
map.replace(3,"a","z");
System.out.println(map.get(3));
//未替换成功,输出cmap.replace(1,"a","z");
System.out.println(map.get(1));
//替换成功,输出z
/*** 7.replace(K key, V value) 方法* 如果map中存在key,则替换成value值,否则返回null*/
// 输出旧的值, a
System.out.println(map.replace(1, "aa"));
// 替换成功,输出新的值, aa
System.out.println(map.get(1));// 不存在key为4, 输出 null
System.out.println(map.replace(4, "d"));
// 不存在key为4, 输出 null
System.out.println(map.get(4));
/*** 8.computeIfAbsent 方法* 如果指定的key不存在,则通过指定的K -> V计算出新的值设置为key的值*/
map.computeIfAbsent(1, key -> key + " computed");
// 存在key为1,则不进行计算,输出值 a
System.out.println(map.get(1));map.computeIfAbsent(4, key -> key + " computed");
// 不存在key为4,则进行计算,输出值 4 computed
System.out.println(map.get(4));
/*** 9.computeIfPresent 方法* 如果指定的key存在,则根据旧的key和value计算新的值newValue,* 如果newValue不为null,则设置key新的值为newValue,* 如果newValue为null, 则删除该key的值,*/
map.computeIfPresent(1, (key, value) -> (key + 1) + value);
// 存在key为1, 则根据旧的key和value计算新的值,输出 2a
System.out.println(map.get(1));map.computeIfPresent(2, (key, value) -> null);
// 存在key为2, 根据旧的key和value计算得到null,删除该值,输出 null
System.out.println(map.get(2));

参考:

深入理解ConcurrentMap.putIfAbsent(key,value) 用法

转载于:https://blog.51cto.com/hanchaohan/2130916

put与putIfAbsent区别相关推荐

  1. java的set和put的区别_put与putIfAbsent区别

    put与putIfAbsent区别: put在放入数据时,如果放入数据的key已经存在与Map中,最后放入的数据会覆盖之前存在的数据, 而putIfAbsent在放入数据时,如果存在重复的key,那么 ...

  2. java.util.Map中put,computeIfAbsent与putIfAbsent区别

    computeIfAbsent和putIfAbsent区别是三点: 1.当Key存在的时候,如果Value获取比较昂贵的话,putIfAbsent就白白浪费时间在获取这个昂贵的Value上(这个点特别 ...

  3. map的put和putIfAbsent区别

    目录 1.putIfAbsent源码 2.putIfAbsent和put的区别 3.案例 1.putIfAbsent源码 default V putIfAbsent(K key, V value) { ...

  4. put和putIfAbsent的区别

    put与putIfAbsent区别: put在放入数据时,如果放入数据的key已经存在与Map中,最后放入的数据会覆盖之前存在的数据, 而putIfAbsent在放入数据时,如果存在重复的key,那么 ...

  5. 滑动窗口类型(Sliding window)

    Sliding window,滑动窗口类型 介绍部分来自:https://www.zhihu.com/question/36738189/answer/908664455 滑动窗口类型的题目经常是用来 ...

  6. java集合框架(集合类)

    目录 集合框架体系图 List列表特点 ArrayList存储结构​ LinkedList存储结构 ArrayList集合常用方法 LinkedList集合常用方法 ArrayList与LinkedL ...

  7. 【易懂】Java源码角度分析put()与putIfAbsent()的区别——源码分析系列

    一.put()方法 1. 源码分析 Java中并未给出put()的源码,因此我们看一下put()方法中给出的注释: Associates the specified value with the sp ...

  8. JAVA8 Map新方法:compute,computeIfAbsent,putIfAbsent与put的区别

    本文参考自:Java8(3):Java8 中 Map 接口的新方法 不管存不存在key,都设值: 1. put put返回旧值,如果没有则返回null @Testpublic void testMap ...

  9. ConcurrentMap的putIfAbsent与put的区别

    首先putIfAbsent与put都可以往map中添加内容,但它们在添加的时候有着很大的不同,一不注意,就会采坑.putIfAbsent在添加的时候会验证hash值,如果hash值一样,则不会更新va ...

最新文章

  1. java开源springboot项目_springBoot 搭建web项目(前后端分离,附项目源代码地址)...
  2. 网易2017校招编程:计算糖果
  3. 与用户登录有关的命令w who whoami last lastb lastlog
  4. a:hover伪类在ios移动端浏览器内点击无效的解决方法
  5. python之random.shuffle
  6. java多线程-线程池
  7. 五种常用的MySQL图形化管理工具
  8. bbsmax mysql_MySQL中自己不太常用的命令
  9. nginx常用配置模板
  10. Python计算中国GDP在那一年超越美国GDP(假设)
  11. 使用u盘如何装linux系统教程视频教程,如何使用u盘安装linux系统
  12. 微服务系统架构设计系列 - RateLimiter - 1. 限流器简介与一般算法
  13. 什么是宽容?你是一个有宽容心的人吗?
  14. MSDN值得学习的地方
  15. 什么是JAVA中的强制类型转换
  16. 基于微信小程序的加油服务系统毕业设计源码
  17. 在 Excel 中查询每个区间并排序
  18. 读书笔记:《流畅的Python》第17章 使用future处理并发
  19. 光伏逆变simlink仿真(MPPT) 最大功率点追踪算法(MPPT)仿真模型,本设计基于扰动观察法(PO)最大功率点跟踪算法追踪光伏电池的发电曲线
  20. Tableau 第十三天 雷达图和凹凸图

热门文章

  1. WebLogic 之安全配置
  2. Linux ACL 权限
  3. Docker服务安全加固
  4. Ubutnu中ln创建软连接失败
  5. Linux安装日文语言包,以及,TeraTerm显示乱码问题 的 解决
  6. 【SQLServer】
  7. scrapy 的依赖库安装和出现def write(self, data, async=False):的解决方法
  8. springboot解决跨域问题(Cors)
  9. [Angular 6] 初学angular,环境全部最新,[ ng serve ] 不能启动,卡在 95% 不动 => 解决方案
  10. JS组件系列——BootstrapTable+KnockoutJS实现增删改查解决方案(三):两个Viewmodel搞定增删改查