How to increase HashMap value using merge method in Java?

I have the following list and use LinkedHashMap and I want to increase the value of the key by 1 (if the key is not present in the map, it starts from 0 and I add +1):

int nums[] = new int[]{4, 10, 5, 4, 2, 10};

Map<Integer, Integer> map = new LinkedHashMap<>();

for (int i = 0; i < nums.length; i++) {
    int key = nums[i];
    int value = map.getOrDefault(key, 0) + 1;

    // I want to use merge method, but have no idea 
    // what should be the 3 rd parameter denoted by "<??????>"
    int value = map.merge(key, 1, <??????>)

    map.put(key, value);
}

However, I want to use merge method, but have no idea what should be the 3 rd parameter denoted by "<??????>" (see the code). So, how can I use merge method in this scenario?

>Solution :

The third parameter of the merge method is a BiFunction, i.e. a functional interface accepting two parameters of generic type V (the type of your values) and returning the merge of said values.

The merge operation is up to you, in your case it simply consists in keeping the first value (the one already present within your map), incrementing it by one and ignoring the second value. The merge could also simply consist in summing the first and second values as for each key you’re just mapping the value 1.

Here is an example based in your code

int nums[] = new int[]{4, 10, 5, 4, 2, 10};

Map<Integer, Integer> map = new LinkedHashMap<>();
for (int i = 0; i < nums.length; i++) {
    map.merge(nums[i], 1, (v1, v2) -> v1 + 1);

    //Alternatively summing the two values
    map.merge(nums[i], 1, (v1, v2) -> v1 + v2);
}

System.out.println(map);

Leave a Reply