Created
August 15, 2008 13:30
-
-
Save shenie/5571 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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