聊一聊Java8中map的putIfAbsent,computeIfAbsent 方法

qq_38807606發表於2020-12-22

1.

//具體用法
// putIfAbsent 和 computeIfAbsent 都是針對map裡沒有key對應的元素進行操作,
// putIfAbsent(Object key ,Object value ) ;computeIfAbsent(Object key , Function) Function是可以code的
// key有對應的value值不進行操作,並返回這個舊值
// key沒有有對應的value值 進行操作 操作 :putIfAbsent 放入newValue ;computeIfAbsent 放入newValue

先上才藝:

/java 8 map (併發map和普通hashMap 都有) 的 常用方法
        //說明:假設有這麼一個容器 Map<String, List> concurrentHashMap = new ConcurrentHashMap<>()
        //有一些學生,年齡介於20到22之間,要根據年齡對這些學生分組
        // java
        List<Student> studentList = Arrays.asList(
                new Student("xiaoming20","20"),new Student("lihua20","20"),new Student("wumei20","20"),
                new Student("xiaoming21","21"),new Student("lihua21","21"),new Student("wumei21","21"),
                new Student("xiaoming22","22"),new Student("lihua22","22"),new Student("wumei22","22")
        );
        //法① list.stream().collect(Collectors.groupingBy(User::getType));
        Map<String,List<Student>> studentGroupMap1 = studentList.stream().collect(Collectors.groupingBy(Student::getAge));
        //java 8 之前
        Map<String, List> before8Map = new ConcurrentHashMap<String, List>();
        for (Student student : studentList) {
           if(CollectionUtils.isEmpty(before8Map.get(student.getAge()))){
              List stuList =  new ArrayList<Student>();
               stuList.add(student);
               before8Map.put(student.getAge(),stuList);
           }else{
               List stuList =  before8Map.get(student.getAge());
               stuList.add(student);
           };
        }
        //java 8 之後,除了法① ,還可以用 putIfAbsent key沒有value就建立,有的話直接拿出來,不用自己判斷
        Map<String, List> after8Map = new ConcurrentHashMap<String, List>();
        studentList.stream().forEach(student ->{
          List<Student> groupList = after8Map.computeIfAbsent(student.getAge() , value->{
               return new ArrayList<Student>();
           });
          //對拿出來的集合操作,不進行這一步,after8Map 拿出來的三個集合都是空的
            groupList.add(student);
       });
        System.out.println(studentGroupMap1.toString());
        System.out.println(before8Map.toString());
        System.out.println(after8Map.toString());

       
        Map<String, List> concurrentHashMap = new ConcurrentHashMap<>();
        //判斷容器裡 list 的value ,value 為null 就建立一個,否則拿出來
        List list = concurrentHashMap.computeIfAbsent("list", k -> {
            return new ArrayList<String>();
        });
        list.add("hello");
        // list.add("hello") 是在陣列裡的 List集合進行操作,根據list再次找到這個list ,發現list1 也是有值的
        List list1 = concurrentHashMap.get("list");
        //在map中已經存在的key的value進行操作。只對已經存在key的進行操作,其他不操作,下面的操作沒用
        // list2 為 null
        List list2 = concurrentHashMap.computeIfPresent("list2" ,(k,v) -> {
            return new ArrayList(10);
        });
        // list3 有個元素:hello
        List list3 = concurrentHashMap.computeIfAbsent("list", k -> {
            return new ArrayList<String>();
        });
        list3.add("word");
        //"list" 有對應的value,則返回舊的value,不繼續執行  new ArrayList<String>() 這個操作
        List list4 = concurrentHashMap.computeIfAbsent("list", k -> {
            return new ArrayList<String>();
        });
        //list4 有兩個元素
        //System.out.println(list4.size());
        //
        ConcurrentHashMap<String, String> map = new ConcurrentHashMap<>();
        map.put("1","1");
        String result = map.putIfAbsent("1","2");
        String result2 = map.get("1");
        map.putIfAbsent("2","2");
        String result3 = map.get("2");

列印結果如下:

{22=[Student{name='xiaoming22', age='22'}, Student{name='lihua22', age='22'}, Student{name='wumei22', age='22'}], 20=[Student{name='xiaoming20', age='20'}, Student{name='lihua20', age='20'}, Student{name='wumei20', age='20'}], 21=[Student{name='xiaoming21', age='21'}, Student{name='lihua21', age='21'}, Student{name='wumei21', age='21'}]}
{22=[Student{name='xiaoming22', age='22'}, Student{name='lihua22', age='22'}, Student{name='wumei22', age='22'}], 20=[Student{name='xiaoming20', age='20'}, Student{name='lihua20', age='20'}, Student{name='wumei20', age='20'}], 21=[Student{name='xiaoming21', age='21'}, Student{name='lihua21', age='21'}, Student{name='wumei21', age='21'}]}
{22=[Student{name='xiaoming22', age='22'}, Student{name='lihua22', age='22'}, Student{name='wumei22', age='22'}], 20=[Student{name='xiaoming20', age='20'}, Student{name='lihua20', age='20'}, Student{name='wumei20', age='20'}], 21=[Student{name='xiaoming21', age='21'}, Student{name='lihua21', age='21'}, Student{name='wumei21', age='21'}]}

 

相關文章