Skip to content

Instantly share code, notes, and snippets.

@lucascs
Created February 21, 2011 20:48
Show Gist options
  • Save lucascs/837684 to your computer and use it in GitHub Desktop.
Save lucascs/837684 to your computer and use it in GitHub Desktop.
Programação funcional em Java
public class Calculadora {
private static final Prova _ = of(Prova.class);
public double mediaDeProvas(List<Prova> provas) {
return mediaPonderada(provas, function(_.getNota()), function(_.getPeso()));
}
public <T> double mediaPonderada(List<T> lista, Function<T, Double> valor, Function<T, Double> peso) {
double soma = 0.0;
double somaPesos = 0.0;
for (T t : lista) {
soma += valor.apply(t) * peso.apply(t);
somaPesos += peso.apply(t);
}
return soma/somaPesos;
}
private <T> Function<Prova, T> function(T ignore) {
return Funcional.function(ignore);
}
}
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.List;
import net.vidageek.mirror.dsl.Mirror;
import br.com.caelum.vraptor.proxy.MethodInvocation;
import br.com.caelum.vraptor.proxy.ObjenesisProxifier;
import br.com.caelum.vraptor.proxy.SuperMethod;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
public class Funcional {
private static final ThreadLocal<Method> _method = new ThreadLocal<Method>();
private static final ThreadLocal<Object[]> _args = new ThreadLocal<Object[]>();
public static <F,T> Function<F, T> function(T value) {
final Method method = _method.get();
final Object[] args = _args.get();
return new Function<F, T>() {
public T apply(F f) {
return (T) new Mirror().on(f).invoke().method(method).withArgs(args);
}
};
}
public static <T> T of(Class<T> type) {
return new ObjenesisProxifier().proxify(type, new MethodInvocation<T>() {
@Override
public Object intercept(T proxy, Method metodo, Object[] args, SuperMethod superMethod) {
_method.set(metodo);
_args.set(args);
return null;
}
});
}
}
public class Prova {
private double nota;
private double peso;
public Prova(double nota, double peso) {
this.nota = nota;
this.peso = peso;
}
public double getNota() {
return nota;
}
public double getPeso() {
return peso;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment