Here is the complete working Java code equivalent to the functional pseudocode you have given in your post:
import java.util.*;
interface Function1<A, B> {
public B apply(final A a);
}
class Main {
public static <A, B> List<Function1<A, B>> addFunc(final Function1<A, B> f, final List<Function1<A, B>> fs) {
final List<Function1<A, B>> gs = new ArrayList<Function1<A, B>>();
gs.addAll(fs);
gs.add(f);
return gs;
}
public static <A, B> List<B> applyAllFuncs(final List<Function1<List<A>, B>> fs, final List<A> as) {
final List<B> bs = new ArrayList<B>();
for(final Function1<List<A>, B> f : fs) {
bs.add(f.apply(as));
}
return bs;
}
public static Function1<List<Double>, Double> min = new Function1<List<Double>, Double>() {
public Double apply(final List<Double> xs) {
double mx = xs.get(0);
for(final Double x : xs) {
if(x < mx) {
mx = x;
}
}
return mx;
}
};
public static Function1<List<Double>, Double> avg = new Function1<List<Double>, Double>() {
public Double apply(final List<Double> xs) {
double sum = 0;
for(final Double x : xs) {
sum += x;
}
return sum / xs.size();
}
};
public static Function1<List<Double>, Double> max = new Function1<List<Double>, Double>() {
public Double apply(final List<Double> xs) {
double mx = xs.get(0);
for(final Double x : xs) {
if(x > mx) {
mx = x;
}
}
return mx;
}
};
public static void main(final String[] args) {
final List<Double> myArray = Arrays.asList(3.0, 8, 1, 2, 9);
List<Function1<List<Double>, Double>> funcs = new ArrayList<Function1<List<Double>, Double>>();
funcs = addFunc(min, funcs);
final List<Function1<List<Double>, Double>> funcs1 = addFunc(max, funcs);
final List<Double> answers = applyAllFuncs(funcs1, myArray);
final List<Function1<List<Double>, Double>> funcs2 = addFunc(avg, funcs);
final List<Double> answers2 = applyAllFuncs(funcs2, myArray);
System.out.println(answers + "\n" + answers2);
}
}
Much of this boilerplate could be avoided if you use already existing functional programming libraries for Java, such as Functional Java or the one offered by GridGain.
Not much of this gets optimized away, as JVM was never intended for this sort of stuff. Scala, which is a functional language on JVM, uses the same methods as above for the implementation of lambdas and higher order functions, and gives on par performance with Java. Still I advise that you should profile the code and decide if it satisfies the performance requirements of your particular use case.