put在放入數據時,如果放入數據的key已經存在與Map中,最后放入的數據會覆蓋之前存在的數據,

而putIfAbsent在放入數據時,如果存在重復的key,那么putIfAbsent不會放入值。

 1.put

   @Test
    public void test3(){
        Map map = new HashMap();
        map.put(1, "AA");
        map.put(2, "BB");
        map.put(3, "CC");
        map.put(1, "DD");
        map.forEach((key, value) -> System.out.println(key + ":" + value));
    }

 

2.putIfAbsent

putIfAbsent   如果傳入key對應的value已經存在,就返回存在的value,不進行替換。如果不存在,就添加key和value,返回null

@Test
    public void test3(){
        Map map = new HashMap();
        map.put(1, "AA");
        map.put(2, "BB");
        map.put(3, "CC");
        Object obj = map.putIfAbsent(1, "EE");
        System.out.println(obj);
        map.forEach((key, value) -> System.out.println(key + ":" + value));
    }