How to increment a map value in Java

2 Answers

0 votes
import java.util.HashMap;
import java.util.Map;
 
public class MyClass
{
    public static<K> void IncrementMapValue(Map<K, Integer> map, K key) {
        map.putIfAbsent(key, 0);
        map.put(key, map.get(key) + 1);
    }
 
    public static void main(String[] args)
    {
        Map<String, Integer> hm = new HashMap();
        
        hm.put("Java", 1);
        hm.put("python", 2);

        IncrementMapValue(hm, "Java");
        IncrementMapValue(hm, "python");
        IncrementMapValue(hm, "rust");

        System.out.println(hm);
    }
}




/*
run:

{Java=2, rust=1, python=3}

*/

 



answered Mar 17, 2023 by avibootz
0 votes
import java.util.HashMap;
import java.util.Map;
 
public class MyClass
{
    public static<K> void IncrementMapValue(Map<K, Integer> map, K key) {
        map.merge(key, 1, Integer::sum);
    }
 
    public static void main(String[] args)
    {
        Map<String, Integer> hm = new HashMap();
        
        hm.put("Java", 1);
        hm.put("python", 2);

        IncrementMapValue(hm, "Java");
        IncrementMapValue(hm, "python");
        IncrementMapValue(hm, "rust");

        System.out.println(hm);
    }
}




/*
run:

{rust=1, Java=2, python=3}

*/

 



answered Mar 17, 2023 by avibootz

Related questions

1 answer 109 views
1 answer 153 views
1 answer 126 views
1 answer 140 views
1 answer 78 views
1 answer 112 views
...