Skip to content

Instantly share code, notes, and snippets.

@chermehdi
Created April 26, 2019 18:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chermehdi/9b3fe691d5333999dd5e663a53de3659 to your computer and use it in GitHub Desktop.
Save chermehdi/9b3fe691d5333999dd5e663a53de3659 to your computer and use it in GitHub Desktop.
package io.github.chermehdi.lib.ds;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.function.Supplier;
/**
* @author MaxHeap
**/
public class CountingMap<T> {
private Map<T, Integer> map;
private final Supplier<Integer> defaultDataProvider;
public CountingMap() {
map = new HashMap<>();
defaultDataProvider = () -> 0;
}
public CountingMap(Supplier<Integer> defaultDataProvider) {
map = new HashMap<>();
this.defaultDataProvider = defaultDataProvider;
}
public CountingMap(int n) {
map = new HashMap<>(n);
defaultDataProvider = () -> 0;
}
public CountingMap(CountingMap<T> map) {
this.map = new HashMap<>(map.map);
defaultDataProvider = () -> 0;
}
public static <T> CountingMap<T> from(T... arr) {
CountingMap<T> map = new CountingMap<>();
for (T el : arr) {
map.increment(el);
}
return map;
}
public static <T> CountingMap<T> from(List<T> arr) {
CountingMap<T> map = new CountingMap<>();
for (T el : arr) {
map.increment(el);
}
return map;
}
public void increment(T key) {
incrementBy(key, 1);
}
public Integer put(T key, Integer value) {
return map.put(key, value);
}
public boolean containsKey(Object key) {
return map.containsKey(key);
}
public void clear() {
map.clear();
}
public Set<T> keySet() {
return map.keySet();
}
public void incrementBy(T key, Integer step) {
map.put(key, map.getOrDefault(key, 0) + step);
}
public void decrement(T key) {
decrementBy(key, 1);
}
public void decrementBy(T key, Integer step) {
Integer value = map.get(key);
if (value != null) {
map.put(key, value - step);
if (value - step <= 0) {
map.remove(key);
}
}
}
public int incrementAndGet(T val) {
return incrementAndGet(val, 1);
}
public int incrementAndGet(T val, int by) {
int old = map.getOrDefault(val, 0);
map.put(val, old + by);
return old + by;
}
public Integer getOrDefault(T value, Integer def) {
return map.getOrDefault(value, def);
}
@Override
public String
toString() {
return "CountingMap{" +
"map=" + map +
'}';
}
public int get(T val) {
Integer value = map.get(val);
if (value == null) {
return defaultDataProvider.get();
}
return value;
}
public Set<Entry<T, Integer>> entrySet() {
return map.entrySet();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment