Skip to content

Instantly share code, notes, and snippets.

@hughrawlinson
Last active February 11, 2016 11:39
Show Gist options
  • Save hughrawlinson/f945cec3235e27f0870e to your computer and use it in GitHub Desktop.
Save hughrawlinson/f945cec3235e27f0870e to your computer and use it in GitHub Desktop.
A histogram class in Java using Lambdas that I was quite proud of
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.function.Function;
public class Histogram <U> {
private SortedMap<Integer, U> result;
public <T> Histogram(Collection<T> data, Function<T, U> func) {
if(data == null){
this.result = new TreeMap<Integer, U>();
} else {
Map<U, Integer> datamap = new HashMap<U,Integer>();
result = new TreeMap<Integer,U>(Collections.reverseOrder());
for(T s : data){
U key = func.apply(s);
int value = datamap.containsKey(key)?(int) datamap.get(key)+1:1;
datamap.put(key, value);
}
for(U s : datamap.keySet()){
this.result.put(datamap.get(s), s);
}
}
}
public Histogram(Collection<U> data) {
this(
data,
Function.identity()
);
}
public Collection<U> getResult() {
return this.result.values();
}
public String toString() {
return result.toString();
}
public Collection<U> getTopNResults(int n){
Iterator<U> it = getResult().iterator();
Collection<U> outColl = new ArrayList<U>();
for(int i = 0;it.hasNext() && i < n; i++){
outColl.add(it.next());
}
return outColl;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment