Skip to content

Instantly share code, notes, and snippets.

@shenie
Created August 15, 2008 13:30
Show Gist options
  • Save shenie/5571 to your computer and use it in GitHub Desktop.
Save shenie/5571 to your computer and use it in GitHub Desktop.
import org.junit.Assert;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
public class MapReduce<V, T> {
private Collection<V> collection;
private T param;
public static <V, T> MapReduce<V, T> reduce(Collection<V> coll, T arg) {
return new MapReduce<V, T>(coll, arg);
}
private MapReduce(Collection<V> coll, T param) {
collection = coll;
this.param = param;
}
public T runBlock(Transformer<V, T> transformer) {
for (V obj : collection) {
param = transformer.execute(param, obj);
}
return param;
}
public static interface Transformer<V, T> {
T execute(T singleEntry, V result);
}
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>();
list.add("abc");
list.add("www");
Integer result = MapReduce.reduce(list, 0).runBlock(new Transformer<String, Integer>() {
public Integer execute(Integer total, String str) {
return total + str.length();
}
});
Assert.assertEquals(6, result.intValue());
Map mappings = MapReduce.reduce(list, new HashMap()).runBlock(new Transformer<String, HashMap>() {
public HashMap execute(HashMap total, String str) {
if (str.equals("abc")) {
total.put("a", str);
}
return total;
}
});
YamlDumper.dump(mappings);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment