Introduction to the merge method of map in jdk8

1. Introduction to map.merge method

jdk8 extends the functions of function oriented, lambda expression and method reference for many common classes, which makes java function oriented programming more convenient. The Map.merge method is one of them. The merge method has three parameters, key: key in map, value: value passed in by the user, remappingFunction: BiFunction function interface (the interface receives two values, performs custom functions and returns the final value). When the specified key does not exist in the map, the value passed in will be set as the value of the key. When the key has a value, execute a method that receives the old value of the key and the value passed in, and execute a custom method to return the final result set as the value of the key.

Attach source code

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

2. Usage scenario of map. Merge() method

There are many scenes used in the merge method. Here is a small Chestnut: the names of people of all ages are counted by age.

    public static void main(String[] args) {
        //Store test data, imitate the data read from the database
        List<user> list = new ArrayList<>();
        user u1 = new user("Li Si", 20);
        user u2 = new user("Zhang San", 30);
        user u3 = new user("Old Wang next door", 18);
        user u4 = new user("Split Lao Luo", 18);
        list.add(u1);
        list.add(u2);
        list.add(u3);
        list.add(u4);

        //Final merge data
        Map<Integer, Set<String>> map = new HashMap<>();
        list.forEach(uVo -> {
            //New HashSet < string > () {}} I don't know how to write it. I feel so handsome
            map.merge(uVo.getAge(), new HashSet<String>() {
                {
                    add(uVo.getName());
                }
            }, (oldV, newV) -> {
                oldV.addAll(newV);
                return oldV;
            });
        });
        System.out.println(map);
    }

Output results:

{18 = [next door Lao Wang, split Lao Luo], 20 = [Li Si], 30 = [Zhang San]}

Tags: Java Lambda Programming Database

Posted on Tue, 28 Apr 2020 08:34:48 -0700 by tronicsmasta