Skip to content

Instantly share code, notes, and snippets.

@Gerhut
Created September 22, 2013 12:27
Show Gist options
  • Save Gerhut/6659444 to your computer and use it in GitHub Desktop.
Save Gerhut/6659444 to your computer and use it in GitHub Desktop.
Java简单实现MapReduce列表
package net.gerhut.functionaljava;
import java.lang.reflect.Array;
import java.util.Arrays;
public class SimpleList<E> {
public static interface SingleArgFunction<E> {
E apply(E arg);
}
public static interface DoubleArgsFunction<E> {
E apply(E arg1, E arg2);
}
private E[] entries;
private int length;
public SimpleList(E ...args) {
entries = args;
length = entries.length;
}
public SimpleList<E> map(SingleArgFunction<E> func) {
SimpleList<E> result = new SimpleList<E>();
if (length > 0) {
E[] resultEntries = (E[])Array.newInstance(entries.getClass().getComponentType(), length);
for (int i = 0, l = entries.length; i < l; i++)
resultEntries[i] = func.apply(entries[i]);
result.entries = resultEntries;
result.length = length;
}
return result;
}
public E reduce(DoubleArgsFunction<E> func) {
E result = null;
if (length > 0) {
result = entries[0];
for (int i = 1, l = entries.length; i < l; i++)
result = func.apply(result, entries[i]);
}
return result;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof SimpleList)) return false;
return Arrays.equals(entries, ((SimpleList<E>)obj).entries);
}
@Override
public int hashCode() {
int code = 0;
for (int i = 0, l = entries.length; i < l; i++)
code += entries[i].hashCode();
return code;
}
@Override
public String toString() {
if (length > 0) {
StringBuilder sBuilder = new StringBuilder();
for (int i = 0, l = entries.length; i < l; i++) {
sBuilder.append(sBuilder.length() == 0 ? "[": ", ");
sBuilder.append(entries[i]);
}
return sBuilder + "]";
} else {
return "Nil";
}
}
public static void main(String args[]) {
SimpleList<Integer> sl = new SimpleList<Integer>(1, 2, 3, 4, 5);
System.out.println(sl.map(new SingleArgFunction<Integer>() {
@Override
public Integer apply(Integer args) {
return args * args;
}
}).reduce(new DoubleArgsFunction<Integer>() {
@Override
public Integer apply(Integer arg1, Integer arg2) {
return arg1 + arg2;
}
}));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment