put與putIfAbsent區別

put與putIfAbsent區別:java

put在放入數據時,若是放入數據的key已經存在與Map中,最後放入的數據會覆蓋以前存在的數據,json

而putIfAbsent在放入數據時,若是存在重複的key,那麼putIfAbsent不會放入值。ide


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


底層實現:spa

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

例子:
.net

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

            輸出結果:orm

                

            key : 1 , value : WangWublog

            key : 2 , value : LiSirem

            key : 1 , value : 張三get

            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));
//未刪除成功,輸出a

map.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));
//未替換成功,輸出c

map.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) 用法

相關文章
相關標籤/搜索