Functions和Predicates介绍和使用
Functions: 主要用于产生各种Function
-
Function 可以进行函数式编程,其中的数据也以key_value的形式进行存储
-
Function作为一个接口,主要使用的是apply()方法,进行对象转换
-
初始化一个Function 需要重写apply()方法
-
-
Functions 主要用于对Function的使用
-
forMap(), 将Map实例转换为Function实例
-
toStringFunction(), 产生一个Function<Object, String>实例,String 为Object对象的toString()方法返回值,两者一一对应。
-
compose(), 参数是两个Function实例。
-
@Test
public void test1() {
Map<String, Long> stringLong = new HashMap<String, Long>();
stringLong.put("key1", 1L);
stringLong.put("key2", 2L);
//将Map实例转换为Function实例
Function<String, Long> stringLongFunction = Functions.forMap(stringLong, 0L);
// 1
System.out.println(stringLongFunction.apply("key1"));
/* 第一个Function是定义转换规则,对第二个Function的value进行处理,
* 下面栗子里,用新建的Function对stringLongFunction的value进行处理,规则就是重写的apply()方法
*/
Function<String, String> compose = Functions.compose(new Function<Long, String>() {
@Override
public String apply(Long input) {
return input * input + "";
}
}, stringLongFunction);
Function<String, String> compose1 = Functions.compose(new Function<String, String>() {
@Override
public String apply(String input) {
return input + input;
}
}, compose);
// 44 = "2*2" + "2*2"
System.out.println(compose1.apply("key2"));
}
Predicates: 主要用于产生各种Predicate
-
Predicate 断言。
-
对参数进行判断,判断依据是重写的apply()方法,返回结果是布尔值
-
初始化一个Predicate 需要重写apply()方法
-
-
Predicates 产生各种各样的Predicate
-
alwaysTrue()和alwaysFalse() 永远返回true或者false
-
isNull()和notNull() 根据是否为空返回true和false
-
and(Predicate A, Predicate B) 和 or(Predicate A, Predicate B) 两个断言的交集或者并集
-
Predicates.compose(Predicate A, FunctionA); 对FunctionA 的value进行判断,判断规则是
Predicate B,查看时通过key来进行查看。
-
@Test
public void test3() {
Map<String, Long> stringLong = new HashMap<String, Long>();
stringLong.put("key1", 1L);
stringLong.put("key3", 3L);
Function<String, Long> stringLongFunction = Functions.forMap(stringLong, 0L);
//true,false
System.out.println(Predicates.alwaysTrue().apply(1));
System.out.println(Predicates.isNull().apply(1));
//多个组合
Predicate<Object> or = Predicates.or(Predicates.isNull(), Predicates.notNull());
//true,true
System.out.println(or.apply(null));
System.out.println(or.apply("1"));
Predicate<Long> and = Predicates.and(new Predicate<Long>() {
@Override
public boolean apply(Long input) {
return input < 5;
}
}, new Predicate<Long>() {
@Override
public boolean apply(Long input) {
return input > 2;
}
});
Predicate<String> compose = Predicates.compose(and, stringLongFunction);
System.out.println("--------Predicate----------");
//false,true
System.out.println(compose.apply("key1"));
System.out.println(compose.apply("key3"));
//转换为Function
Function<Long, Boolean> longBoolean = Functions.forPredicate(and);
System.out.println("--------Predicate-Function---------");
//true,false
System.out.println(longBoolean.apply(3L));
System.out.println(longBoolean.apply(6L));
}