BiFunction接受两个任意类型参数并返回一个任意类型对象
@FunctionalInterface
public interface BiFunction<T, U, R> {
R apply(T t, U u);
}
BiFunction 与Function连用
private void bifunction() {
BiFunction<Integer,Integer,Double> biFunction = (a,b)->Math.pow(a,b);
Function<Double,String> function = a->"result:"+String.valueOf(a);
System.out.println(biFunction.andThen(function).apply(3,4));
}
BiFunction与Function作为参数
private void bifunction2(BiFunction<Integer,Integer,Double> biFunction
, Function<Double,String> function
, Integer a,Integer b) {
String s = biFunction.andThen(function).apply(a,b);
System.out.println(s);
}
private void bifunction3() {
BiFunction<Integer,Integer,Double> biFunction = (a,b)-> Math.pow(a,b);
Function<Double,String> function = a->"result:"+a;
bifunction2(biFunction,function,3,4);
}
BiFunction作为工厂
private void biFuncFac2(){
GPS gps = biFunctionFac("40.741895", "-73.989308", GPS::new);
System.out.println(gps);
}
private <R extends GPS> R biFunctionFac(String lat, String lon, BiFunction<String,String,R> biFunction){
return biFunction.apply(lat, lon);
}
BiFunction作为filter
private <T,U,R> List<R> biFunFilter(List<T> list, U cond, BiFunction<T,U,R> biFunction) {
List<R> result = new ArrayList<>();
for (T t : list) {
R r = biFunction.apply(t,cond);
if (!Objects.isNull(r)) {
result.add(r);
}
}
return result;
}
private void biFunFilter2() {
List<String> list = Arrays.asList("node", "c++", "java", "javascript");
//BiFunction<String,Integer,String> biFunction = ()
List<String> list1 = biFunFilter(list, 3, (a,size)-> {
if (a.length() > size) {
return a;
} else {
return null;
}
});
System.out.println(list1);
List<String> list2 = biFunFilter(list, "c", (a, cond)->{
if (a.startsWith(cond)) {
return a;
} else {return null;}
});
System.out.println(list2);
List<Integer> number = Arrays.asList(1,2,3,4,5,6,7);
List<Integer> list3 = biFunFilter(number, 2, (a, cond)->{
if (a % cond == 0) {
return a;
} else {return null;}
});
System.out.println(list3);
}