一开始。我觉得java也可以函数式编程啊,如下代码。
public class TestMapLike {
public static void main(String[] args) {
Object[] arr = new Object[]{1, 2, 3, 4, 5};
map(donothing(arr));
System.out.println(Arrays.toString(arr));
}
public static void map(Object[] arr) {
for (int i = 0; i < arr.length; i++) {
arr[i] = (Integer)arr[i]*2;
}
}
public static Object[] donothing(Object[] arr) {
return arr;
}
}
看map函数,里面也有函数。
但是…
先看java版函数式编程实现map
定义接口,就是函数
public interface Func {
public Object invoke(Object ...o);
}
python里map的实现
import java.util.Arrays;
public class TestMap {
public static void main(String[] args) {
Object[] arr = new Object[]{1, 2, 3, 4, 5};
map(arr, new Func() {
@Override
public Object invoke(Object ...o) {
return (Integer)o[0] * 2;
}
});
System.out.println(Arrays.toString(arr));//output [2, 4, 6, 8, 10]
}
public static void map(Object[] arr, Func function) {
for (int i = 0; i < arr.length; i++) {
arr[i] = function.invoke(arr[i]);
}
}
}
对应到python
map(lambda x:x*2,[1,2,3,4,5])
reduce的java实现
public class TestReduce {
public static void main(String[] args) {
Object sum = sum(new Object[]{0, 1, 2, 3, 4});
Object str = join(new Object[]{0, 1, 2, 3, 4});
System.out.println(sum);//output 10
System.out.println(str);//output 01234
}
private static Object join(Object[] objects) {
return reduce(objects, "", new Func() {
@Override
public Object invoke(Object... o) {
return o[0].toString() + o[1];
}
});
}
public static Object sum(Object[] arr) {
return reduce(arr, 0, new Func() {
@Override
public Object invoke(Object ...o) {
return (Integer)o[0] + (Integer)o[1];
}
});
}
private static Object reduce(Object[] arr, Object init, Func f) {
Object sum = init;
for (int i = 0; i < arr.length; i++) {
sum = f.invoke(sum, arr[i]);
}
return sum;
}
}