java8 Function函数编程详解
Function函数基础定义和使用
public static void t1(){
Function<Integer,Integer> calSum= x -> x+2;
Integer apply = calSum.apply(2);
System.out.println(apply);
}
执行结果:
4
多个Function的执行
public static void t2(){
Function<Integer,Integer> calFn1= x -> x+2;
Function<Integer,Integer> calFn2= x -> x*10;
//先算calFn2 在执行calF1
Integer apply = calFn1.compose(calFn2).apply(4);
System.out.println(apply);
//先算calFn1 在执行calF2
Integer apply1 = calFn1.andThen(calFn2).apply(4);
System.out.println(apply1);
}
执行结果:
42
60
Function对象操作
对象
import lombok.Data;
/**
* 汽车
*/
@Data
public class Car {
private String name;
private String company;
private Integer status;
/**
* 设置名称并返回当前对象
* @param name
* @return
*/
public Car setName(String name){
this.name=name;
return this;
}
/**
* 设置公司并返回当前类
* @param company
* @return
*/
public Car setCompany(String company){
this.company=company;
return this;
}
@Override
public String toString() {
return "name:"+name+" company:"+company;
}
}
对象处理函数
public static void t3(){
Function<Car,Car> setNameFn=car->{
car.setName("长城");
return car;
};
Function<Car,Car> setSecondNameFn=car->{
car.setName(car.getName()+"H6");
return car;
};
Car apply = setNameFn.andThen(setSecondNameFn).apply(new Car());
System.out.println(apply);
}
执行结果:
name:长城H6 company:null
原创文章,作者:carmelaweatherly,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/243561.html