All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.ggp.base.util.Counter Maven / Gradle / Ivy

The newest version!
package org.ggp.base.util;

import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Maps;

//TODO: Replace with Multisets (?)
//No, because longs are better than ints
public class Counter {
    private final Map counts = Maps.newHashMap();

    public static  Counter create() {
        return new Counter();
    }

    public synchronized long get(T key) {
        if (counts.containsKey(key)) {
            return counts.get(key);
        } else {
            return 0L;
        }
    }

    public synchronized void increment(T key) {
        if (!counts.containsKey(key)) {
            counts.put(key, 1L);
        } else {
            counts.put(key, 1L + counts.get(key));
        }
    }

    public synchronized void add(T key, long toAdd) {
        if (!counts.containsKey(key)) {
            counts.put(key, toAdd);
        } else {
            counts.put(key, toAdd + counts.get(key));
        }
    }
    public synchronized Set keySet() {
        return ImmutableSet.copyOf(counts.keySet());
    }

    public synchronized Set> entrySet() {
        return ImmutableSet.copyOf(counts.entrySet());
    }

    public synchronized boolean isEmpty() {
        return counts.isEmpty();
    }

    public synchronized void clear() {
        counts.clear();
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy