Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to increase HashMap value using merge method in Java?

I have the following list and use LinkedHashMap.

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 third parameter denoted by "<??????>" (see the code).

So, how can I use merge method in this scenario?


1 Answers

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.

Assuming that in your code you're trying to get the frequency of each key, although you wrote "it starts from 0 and I add +1", here is an example of what you were attempting.

In your case, since for each key you're always mapping the value 1 and then incrementing it, you could implement the BiFunction merge either by summing the two colliding values, (v1, v2) -> v1 + v2, or by adding 1 to the previously mapped value (v1, v2) -> v1 + 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++) {
    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);

However, if your goal was to get the number of key collisions rather than their frequency, then the code above would still work by simply replacing the initial value 1 with 0.

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], 0, (v1, v2) -> v1 + 1);
}

System.out.println(map);
like image 188
dani-vta Avatar answered Nov 03 '25 02:11

dani-vta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!