Skip to content

Instantly share code, notes, and snippets.

@gubatron
Created September 24, 2013 18:34
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 gubatron/6689228 to your computer and use it in GitHub Desktop.
Save gubatron/6689228 to your computer and use it in GitHub Desktop.
Whenever you need to implement a histogram this will save time. Just invoke update(K key) to add one more ocurrence to the underlying map. When you want the histogram in ascending order, invoke histogram() and you will get all the entries and number of ocurrences in a Entry<K,Integer> array.
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class HistoHashMap<K> {
private final Map<K,Integer> map = new HashMap<K, Integer>();
public int update(K key) {
int r = 1;
if (map.containsKey(key)) {
r = 1 + map.get(key);
}
map.put(key, r);
return r;
}
public Integer get(K key) {
return map.get(key);
}
public Entry<K,Integer>[] histogram() {
Set<Entry<K, Integer>> entrySet = map.entrySet();
@SuppressWarnings("unchecked")
Entry<K, Integer>[] array = entrySet.toArray(new Entry[0]);
Arrays.sort(array, new Comparator<Entry<K,Integer>>() {
@Override
public int compare(Entry<K, Integer> o1, Entry<K, Integer> o2) {
return o1.getValue().compareTo(o2.getValue());
}
});
return array;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment