package js_method;
import java.util.List;
public interface CallBack<T_INIT,T_ARRAY> {
T_INIT callBack(T_INIT initValue,T_ARRAY element,int index, List<T_ARRAY> arr);
}
package js_method;
import java.util.List;
public abstract class Reduce<INITVALUE_TYPE,ARRAY_TYPE> implements CallBack<INITVALUE_TYPE,ARRAY_TYPE>{
@Override
public abstract INITVALUE_TYPE callBack(INITVALUE_TYPE initValue, ARRAY_TYPE element, int index, List<ARRAY_TYPE> arr);
public INITVALUE_TYPE reduce(List<ARRAY_TYPE> array,CallBack<INITVALUE_TYPE,ARRAY_TYPE> callBack,INITVALUE_TYPE initvalue) throws Exception {
if(array==null) throw new Exception("must have array!!!");
if(callBack==null) throw new Exception("must have callback function!!!");
int i=0;
if(initvalue == null){
while(i<array.size()){
if(array.get(i)!=null){
initvalue= (INITVALUE_TYPE) array.get(i);
i++;
break;
}
i++;
}
}
for(;i<array.size();i++){
initvalue=callBack(initvalue,array.get(i),i,array);
}
return initvalue;
}
}
package js_method;
import java.util.Arrays;
import java.util.List;
public class UseReduce {
public static void main(String[] args) throws Exception {
Reduce<Integer,Integer> reduce = new Reduce<Integer, Integer>() {
@Override
public Integer callBack(Integer initValue, Integer element, int index, List<Integer> arr) {
return initValue+element;
}
};
Integer reduceRes = reduce.reduce(Arrays.asList(1, 2, 3, 4, 5), reduce, null);
System.out.println(reduceRes);
}
}
|