不管lambda表达式还是Stream流式编程,Function、Consumer、Supplier、Predicate 四个接口是一切函数式编程的基础。下面我们详细学习这四个巨头,
interface Supplier<T>
该接口的中文直译是“提供者”,可以理解为定义一个lambda表达式,没有输入参数,返回一个T类型的值。
1Supplier<Integer> supplier = () -> 10; 2//输出10 3System.out.println(supplier.get());
interface Consumer<T>
该接口的中文直译是“消费”,可以理解为定义一个lambda表达式,接收一个T类型的参数,并且没有返回值。
-
accept :接收参数,并调用Consumer接口里的方法
Consumer<Integer> print = x -> System.out.println(x); //输出10 print.accept(10);
-
andThen:调用完consumer自己后,还调用andThen方法参数中指定的Consumer
Consumer<Integer> print = x -> System.out.println(x); Consumer<Integer> printPlusSelf = x -> System.out.println(x + x);
//输出10以及20 print.andThen(printPlusSelf).accept(10);
interface Function<T, R>
该接口的中文直译是“函数”,可以理解为:定义一个lambda表达式**,**接收一个T类型的参数,返回一个R类型的值。
-
apply:传入一个T类型的参数,返回一个R类型的值
Function<Integer, Integer> plusSelf = x -> x + x;
//apply System.out.println(plusSelf.apply(10));
-
compose:accept获取到的参数,先执行compose里面的Function,再执行原Function
1 //两个function 2 Function<Integer, Integer> plusSelf = x -> { 3 System.out.println("plusSelf"); 4 return x + x; 5 }; 6 Function<Integer, String> toString = x -> { 7 System.out.println("toString"); 8 return String.valueOf(x); 9 }; 10 11 //输出20,整数10先自加变成20,然后由toString转换成字符串 12 String string1 = toString.compose(plusSelf).apply(10); 13 System.out.println(string1); -
andThen:与compose相反。先执行原Function,在执行andThen里面的Function。
1 //两个function 2 Function<Integer, Integer> plusSelf = x -> { 3 System.out.println("plusSelf"); 4 return x + x; 5 }; 6 Function<Integer, String> toString = x -> { 7 System.out.println("toString"); 8 return String.valueOf(x); 9 }; 10 11 //输出20, 先自加,再转换成字符串 12 String string2 = plusSelf.andThen(toString).apply(10); 13 System.out.println(string2);
interface Predicate<T>
该接口的中文直译是“断言”,用于返回false/true。T是lambda表达式的输入参数类型。
-
test :测试test方法中输入参数是否满足接口中定义的lambda表达式
1 Predicate<String> test = x -> "test".equals(x); 2 Predicate<String> test2 = x -> "test2".equals(x); 3 4 //test 5 System.out.println(test.test("test")); //true 6 System.out.println(test.test("test_false")); //false -
and :原 Predicate 接口和 and 方法中指定的 Predicate 接口要同时为true,test方法才为true。与逻辑运算符 && 一致。
1 Predicate<String> test = x -> "test".equals(x); 2 Predicate<String> test2 = x -> "test2".equals(x); 3 4 //and 5 System.out.println(test.and(test2).test("test")); //false -
negate:对结果取反后再输出
1 Predicate<String> test = x -> "test".equals(x); 2 Predicate<String> test2 = x -> "test2".equals(x); 3 4 //negate 5 System.out.println(test.negate().test("test")); //false -
or:原 Predicate 接口和 or 方法中指定的 Predicate 接口只要一个为true,test方法为true。与逻辑运算符 || 一致。
1 Predicate<String> test = x -> "test".equals(x); 2 Predicate<String> test2 = x -> "test2".equals(x); 3 //or 4 System.out.println(test.or(test2).test("test")); //false
相关资料
Java 8 函数式编程系列