public class Stream_02 {
/**
* 函数接口
*/
/**
* Function
*/
public static void main(String[] args) {
Function<Integer,Integer> incr1= (x)->{
System.out.println("执行了默认方法");
return x+1;
};
Function<Integer,Integer> incr2= (x)->{
System.out.println("执行了之后方法");
return x+2;
};
Function<Integer,Integer> incr3= (x)->{
System.out.println("执行了之前方法");
return x+3;
};
int x1=2;
//addThen先执行当前函数的apply方法然后执行addThen的方法
Function<Integer, Integer> andThen = incr1.andThen(incr2);
System.out.println("x1: "+andThen.apply(x1));
//执行了默认方法
//执行了之后方法
//------------- x1 : 5
//compose先执行addThen的方法然后执行当前函数的apply方法
Function<Integer, Integer> andThen1 = incr1.compose(incr3);
System.out.println("x1: "+andThen1.apply(x1));
//执行了之前方法
//执行了默认方法
//------------- x1 : 6
//identity方法来产生一个Function对象,那么其apply方法的作用为:返回所传入apply方法中的参数
Function<Integer, Integer> identity = Function.identity();
Integer apply1 = identity.apply(10);
System.out.println(apply1);
// 10
/**
* BiFunction 两个参数返回一个值
* <T, U, R>
* T是第一个参数类型
* U是第二个参数类型
* R是返回结果的类型
*/
BiFunction<Integer,Integer,Integer> biFun1=(o1,o2)-> o1+o2;
BiFunction<Integer,Integer,Integer> biFun2=Integer::sum;
Integer apply = biFun2.apply(1, 2);
System.out.println(apply);
//3
//高级函数
Function<Integer,Function<Integer,Integer>> bigFun=z->y->z+y;
//返回一个Function
Function<Integer, Integer> bigFun2 = bigFun.apply(1);
Integer apply2 = bigFun2.apply(2);
System.out.println("apply2: "+apply2);
// apply2: 3
//二元函数没有compose能力,只是默认实现了andThen。
/**
* Operator其实就是Function,函数有时候也叫作算子。
*/
//ctrl art shift u
// 算子 UnaryOperator
// 二元算子 UnaryOperator
/**
* minBy 排序后的第一个
* maxBy 排序后的最后一个元素
*/
BinaryOperator<String> min =BinaryOperator.minBy(Comparator.comparing(String::length));
String apply3 = min.apply("100", "2");
System.out.println(apply3);
/**
* Predicate主要作为一个谓词演算推导真假值存在
* 其意义在于帮助开发一些返回bool值的Function
* 其默认方法也封装了and、or和negate逻辑
*
*/
//是否大于5
Predicate<Integer> pre=a->a>5;
if (pre.test(6)){
System.out.println("大于5了");
}
/**
* Consumer<T>
* void accept(T)
* 看名字就可以想到,这像谓词函数接口一样,也是一个Function接口的特殊表达——接受一个泛型参数,不需要返回值的函数接口。
*/
Consumer<Integer> consumer =System.out::println;
//一用到就打印这个值
consumer.accept(100);
/**
* Supplier
* T get()
*/
Supplier<Integer> supplier =()-> (int) (Math.random() * 100);
Integer integer = supplier.get();
System.out.println(integer);
}
}
java8之stream使用之函数接口的使用
最新推荐文章于 2022-08-19 07:59:09 发布