java8提供一系列函数式接口,简化很多操作,直接上代码
public class FunctionUtils {
public static void main(String[] args) {
System.out.println(fun2(2));
System.out.println(fun3(2));
consumer(2);
System.out.println(supplierGetUser());
}
// -------------------Function-------------------
// apply:函数式接口方法,输入T,输出R。
// compose:compose接收一个Function参数,先执行传入的逻辑,再执行当前的逻辑。
// andThen:andThen接收一个Function参数,先执行当前的逻辑,再执行传入的逻辑。
// identity:方便方法的连缀,返回当前对象。
public static int fun1(int i) {
// i = 2时 结果为2 + 2 = 4
Function<Integer, Integer> function = f -> f + f;
return function.apply(i);
}
public static int fun2(int i) {
// i = 2时 结果为 2*2=4 再 4+4 = 8
Function<Integer, Integer> function1 = f -> f + f;
Function<Integer, Integer> function2 = f -> f * f;
return function1.compose(function2).apply(i);
}
public static int fun3(int i) {
// i = 2时 结果为 2+2=4 再 4*4=16
Function<Integer, Integer> function1 = f -> f + f;
Function<Integer, Integer> function2 = f -> f * f;
return function1.andThen(function2).apply(i);
}
//---------------------------Consumer------------------------------
// consumer 表示消费的意思,其实也就是处理其中的逻辑运算 注意!!!无返回值
/**
* 然后调用accept,对这个参数做一系列的操作,没有返回值
*
* @param i 入参
*/
public static void consumer(int i) {
Consumer<Integer> consumer = x -> {
int a = x + 2;
System.out.println(a);// 12
System.out.println(a + "*");// 12*
};
consumer.accept(i);
}
//----------------------------Supplier-------------------------------
// 看语义,可以看到,这个接口是一个提供者的意思,只有一个get的抽象类,
// 没有默认的方法以及静态的方法,传入一个泛型T的,get方法,返回一个泛型T
public static String supplierGet() {
Supplier<String> supplier = String::new;
return supplier.get();
}
public static User supplierGetUser() {
Supplier<User> supplier = User::new;
// 获取这个用户
User user = supplier.get();
user.setName("123");
return user;
}
//----------------------------Predicate------------------------------
// 这个接口可以理解为做判断的意思
/**
* Predicate 使用 判断传进来的值 再做对比判断
*
* @param value 值
* @param predicate 比对
* @return true = 符合预期
*/
public static boolean jug(int value, Predicate<Integer> predicate) {
return predicate.test(value);
}
/**
* 类型多条件判断 xx&&xx 均成立时
*
* @param value 值
* @param predicateOne 条件一的表达式
* @param predicateTwo 条件二的表达式
* @return true = 符合预期
*/
public static boolean jug(int value, Predicate<Integer> predicateOne, Predicate<Integer> predicateTwo) {
return predicateOne.and(predicateTwo).test(value);
}
/**
* 类型多条件判断 xx or xx 或的关系
* negateJug(1, v1 -> v1 > 3, v2 -> v2 < 5)
*
* @param value 值
* @param predicateOne 条件一的表达式
* @param predicateTwo 条件二的表达式
* @return true = 符合预期
*/
public static boolean or(int value, Predicate<Integer> predicateOne, Predicate<Integer> predicateTwo) {
return predicateOne.or(predicateTwo).test(value);
}
/**
* Predicate 使用 判断传进来的值 再做对比判断
* 非的对比 类似x!=x
* negateJug(1, v -> v > 1)
*
* @param value 值
* @param predicate 比对
* @return true = 符合预期
*/
public static boolean negateJug(int value, Predicate<Integer> predicate) {
return predicate.negate().test(value);
}
}
@Data
class User {
private String name;
private String sex;
}
网友评论