科里化
常用于单位转换:
科里化是一种将具备2个参数(比如,x和y)的函数f转化为使用一个参数的函数g,并且这个函数的返回值也是一个函数,它会作为新函数的一个参数。后者的返回值和初始函数的返回值相同,即f(x,y)=(g(x))(y)。
static double converter(double x, double conversionFactor, double baseline) {
return x * conversionFactor + baseline;
}
static DoubleUnaryOperator curriedConverter(double y, double z) {
return (double x) -> x * y + z;
}
double waterBoilingPointInF = converter(100, 9.0 / 5, 32);
System.out.println(waterBoilingPointInF);
DoubleUnaryOperator convertCtoF = curriedConverter(9.0 / 5, 32);//摄氏转为华氏温度
DoubleUnaryOperator convertUSDtoGBP = curriedConverter(0.6, 0);//美元到人民币
DoubleUnaryOperator convertKmtoMi = curriedConverter(0.6214, 0);//公里到英里
System.out.println(convertCtoF.applyAsDouble(100.0));
System.out.println(convertUSDtoGBP.applyAsDouble(100.0));
System.out.println(convertUSDtoGBP.applyAsDouble(200.0));
调试
java8中涉及到lambda表达式的栈跟踪不那么友好,较难理解。
调试时可以使用日志调试。
Stream.of(2, 3, 4, 5)
.peek(x -> System.out.println("taking from stream: " + x))
.map(x -> x + 17)
.peek(x -> System.out.println("after map: " + x))
.filter(x -> x % 2 == 0)
.peek(x -> System.out.println("after filter: " + x))
.limit(3)
.peek(x -> System.out.println("after limit: " + x))
.collect(toList());
设计模式
策略模式:
public class StrategyMain {
public static void main(String[] args) {
// old school
Validator v1 = new Validator(new IsNumeric());
System.out.println(v1.validate("aaaa"));
Validator v2 = new Validator(new IsAllLowerCase ());
System.out.println(v2.validate("bbbb"));
// with lambdas
Validator v3 = new Validator((String s) -> s.matches("\\d+"));
System.out.println(v3.validate("aaaa"));
Validator v4 = new Validator((String s) -> s.matches("[a-z]+"));
System.out.println(v4.validate("bbbb"));
}
interface ValidationStrategy {
public boolean execute(String s);
}
static private class IsAllLowerCase implements ValidationStrategy {
public boolean execute(String s){
return s.matches("[a-z]+");
}
}
static private class IsNumeric implements ValidationStrategy {
public boolean execute(String s){
return s.matches("\\d+");
}
}
static private class Validator{
private final ValidationStrategy strategy;
public Validator(ValidationStrategy v){
this.strategy = v;
}
public boolean validate(String s){
return strategy.execute(s); }
}
}
网友评论