put与putIfAbsent区别

2019-09-28 09:33:18

参考文章 put与putIfAbsent区别

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

        //循环Map
        map.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
 */// 输出旧的值, aSystem.out.println(map.replace(1, "aa"));// 替换成功,输出新的值, aaSystem.out.println(map.get(1));// 不存在key为4, 输出 nullSystem.out.println(map.replace(4, "d"));// 不存在key为4, 输出 nullSystem.out.println(map.get(4));
/**
 * 8.computeIfAbsent 方法
 * 如果指定的key不存在,则通过指定的K -> V计算出新的值设置为key的值
 */map.computeIfAbsent(1, key -> key + " computed");// 存在key为1,则不进行计算,输出值 aSystem.out.println(map.get(1));map.computeIfAbsent(4, key -> key + " computed");// 不存在key为4,则进行计算,输出值 4 computedSystem.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计算新的值,输出 2aSystem.out.println(map.get(1));map.computeIfPresent(2, (key, value) -> null);// 存在key为2, 根据旧的key和value计算得到null,删除该值,输出 nullSystem.out.println(map.get(2));


参考:

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


  • 2019-09-19 09:07:46

    @Autowired用法详解

    在使用@Autowired时,首先在容器中查询对应类型的bean     如果查询结果刚好为一个,就将该bean装配给@Autowired指定的数据     如果查询的结果不止一个,那么@Autowired会根据名称来查找。     如果查询的结果为空,那么会抛出异常。解决方法时,使用required=false

  • 2019-09-19 11:36:58

    注解@Mapper、@MapperScan

    定要变成实现类的接口所在的包,然后包下面的所有接口在编译之后都会生成相应的实现类

  • 2019-09-19 11:46:45

    @EnableConfigurationProperties注解详解,源码

    用springboot开发的过程中,我们会用到@ConfigurationProperties注解,主要是用来把properties或者yml配置文件转化为bean来使用的,而@EnableConfigurationProperties注解的作用是@ConfigurationProperties注解生效。 如果只配置@ConfigurationProperties注解,在IOC容器中是获取不到properties配置文件转化的bean的,当然在@ConfigurationProperties加入注解的类上加@Component也可以使交于springboot管理。

  • 2019-09-19 14:10:03

    Android UI布局优化之ViewStub介绍

    ViewStub的inflate只能被调用一次,第二次调用会抛出异常,setVisibility可以被调用多次,但不建议这么做(文章中说原因)

  • 2019-09-19 14:21:47

    Dubbo和spring cloud微服务框架区别和介绍

    关于 Dubbo 和 Spring Cloud 的相关概念和对比,上面已经叙述的很清楚了,我个人比较倾向于 Spring Cloud,原因就是真正的微服务框架、提供整套的组件支持、使用简单方便、强大的社区支持等等,另外,因为考虑到 .NET/.NET Core 的兼容处理,RPC 并不能很好的实现跨语言(需要借助跨语言库,比如 gRPC、Thrift,但因为 Dubbo 本身就是“gRPC”,在 Dubbo 之上再包一层 gRPC,有点重复封装了),而 HTTP REST 本身就是支持跨语言实现,所以,Spring Cloud 这一点还是非常好的(Dubbox 也支持,但性能相比要差一些)。

  • 2019-09-22 07:12:04

    git Please move or remove them before you can merge

    这是因为本地有修改,与云端别人提交的修改冲突,又没有merge. 如果确定使用云端的代码,最方便的解决方法是删除本地修改,可以使用以下命令: git clean -d -fx

  • 2019-09-22 07:36:52

    ALIN10146-自查方案

    报错原因 1.请求appid应用未上线或者是应用类型是第三方应用 2.签约权限问题 3.签名类型使用错误 4.请求参数问题 5.秘钥匹配问题 6.应用类型问题

  • 2019-09-22 07:37:44

    ALIN10146,ALI38173支付宝APP支付集成时出现的问题

    最近在做支付宝APP的集成,遇到了一堆问题。百度不到,ALI64还好点,ALI38173基本上就没了。我也是测试了很久才解决的。ALI64的解决方案是因为要对私钥有问题。ALI38173是签名有问题。签名的解决方...