jdk1.8的ConcurrentHashMap的merge案例(转)

merge方法有三个参数,key:map中的键,value:使用者传入的值,remappingFunction:BiFunction函数接口(该接口接收两个值,执行自定义功能并返回最终值)。当map中不存在指定的key时,便将传入的value设置为key的值,当key存在值时,执行一个方法该方法接收key的旧值和传入的value,执行自定义的方法返回最终结果设置为key的值。

default V merge(K key, V value,
            BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
        Objects.requireNonNull(remappingFunction);
        Objects.requireNonNull(value);
        V oldValue = get(key);
        V newValue = (oldValue == null) ? value :
                   remappingFunction.apply(oldValue, value);
        if(newValue == null) {
            remove(key);
        } else {
            put(key, newValue);
        }
        return newValue;
    }

merge() 适用于两种情况。如果给定的key不存在,它就变成了put(key, value)。但是,如果key已经存在一些值,我们 remappingFunction 可以选择合并的方式。这个功能是完美契机上面的场景:

只需返回新值即可覆盖旧值: (old, new) -> new
只需返回旧值即可保留旧值:(old, new) -> old
以某种方式合并两者,例如:(old, new) -> old + new
甚至删除旧值:(old, new) -> null

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

class StudentScore{
    private Integer orderNum;
    private String subjectName;
    private Integer score;
    public StudentScore(Integer orderNum,String subjectName,Integer score){
        this.orderNum=orderNum;
        this.subjectName=subjectName;
        this.score=score;
    }
    public Integer getOrderNum(){
        return this.orderNum;
    }
    public String getSubjectName(){
        return this.subjectName;
    }
    public Integer getScore(){
        return this.score;
    }

}
public class ConcurrenthashmapTest2 {
    public static Map<Integer,Integer> sum1(List<StudentScore>list){
        
        Map<Integer, Integer> map = new HashMap<>();
        for (StudentScore studentScore : list) {
            if (map.containsKey(studentScore.getOrderNum())) {
                map.put(studentScore.getOrderNum(), map.get(studentScore.getOrderNum()) + studentScore.getScore());
            } else {
                map.put(studentScore.getOrderNum(), studentScore.getScore());
            }
        }
        return map;
    }
    public static Map<Integer,Integer> sum2(List<StudentScore>list){
        Map<Integer, Integer> map = new HashMap<>();
        list.stream().forEach(studentScore -> map.merge(studentScore.getOrderNum(), studentScore.getScore(), Integer::sum));
        return map;
    }

    public static void main(String args[]){
        List<StudentScore>list=new ArrayList<>();
        list.add(new StudentScore(1, "chinese", 110));
        list.add(new StudentScore(1, "english", 120));
        list.add(new StudentScore(1, "math", 135));
      
        list.add(new StudentScore(2, "chinese", 99));
        list.add(new StudentScore(2, "english", 100));
        list.add(new StudentScore(2, "math", 133));

        System.out.println(sum1(list));
        System.out.println(sum2(list));

    }
}

在这里插入图片描述
拓展
 merge:通过构建BiFunction或则是调用java中的一些函数来操作merge参数中的变量。

compute:通过构建BiFunction或则使用lambda表达式来操作参数中的变量,这里无论key是否存在都会执行后面的方法。

computeIfAbsent,computeIfPresent:前一个是当key不存在是则执性后面的方法,后一个是存在时执行后面的方法。

发布了156 篇原创文章 · 获赞 16 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_44001521/article/details/104414029