Increase Map<K, Integer> counter.get(key) by increase. - Java java.util

Java examples for java.util:Map Operation

Description

Increase Map<K, Integer> counter.get(key) by increase.

Demo Code


//package com.java2s;

import java.util.Map;

public class Main {
    /**/* ww  w  . ja va2s .c om*/
     * Increase counter.get(key) by increase.
     * If value decrease to zero, it is removed from map.
     */
    public static <K> void increaseMapCounter(Map<K, Integer> counter,
            K key, int increase) {
        if (!counter.containsKey(key)) {
            counter.put(key, 0);
        }
        counter.put(key, counter.get(key) + increase);
        if (counter.get(key) == 0) {
            counter.remove(key);
        }
    }
}

Related Tutorials