1、函数式编程 简介
我们最常用的面向对象编程(Java)属于命令式编程(Imperative Programming)这种编程范式。常见的编程范式还有逻辑式编程(Logic Programming),函数式编程(Functional Programming)。
函数式编程作为一种编程范式,在科学领域,是一种编写计算机程序数据结构和元素的方式,它把计算过程当做是数学函数的求值,而避免更改状态和可变数据。
函数式编程并非近几年的新技术或新思维,距离它诞生已有大概50多年的时间了。它一直不是主流的编程思维,但在众多的所谓顶级编程高手的科学工作者间,函数式编程是十分盛行的。
什么是函数式编程?
简单的回答:一切都是数学函数。函数式编程语言里也可以有对象,但通常这些对象都是恒定不变的 —— 要么是函数参数,要什么是函数返回值。函数式编程语言里没有 for/next 循环,因为这些逻辑意味着有状态的改变。相替代的是,这种循环逻辑在函数式编程语言里是通过递归、把函数当成参数传递的方式实现的。
举个例子: a = a + 1
这段代码在普通成员看来并没有什么问题,但在数学家看来确实不成立的,因为它意味着变量值得改变。
2、函数式接口的定义
1、该注解只能标记在"有且仅有一个抽象方法"的接口上。
2、JDK8接口中的静态方法和默认方法,都不算是抽象方法。
3、接口默认继承java.lang.Object,所以如果接口显示声明覆盖了Object中方法,那么也不算抽象方法。
4、该注解不是必须的,如果一个接口符合"函数式接口"定义,那么加不加该注解都没有影响。加上该注解能够更好地让编译器进行检查。如果编写的不是函数式接口,但是加上了@FunctionInterface,那么编译器会报错。
在java8中,满足下面任意一个条件的接口都是函数式接口:
1、被@FunctionalInterface注释的接口,满足@FunctionalInterface注释的约束。
2、没有被@FunctionalInterface注释的接口,但是满足@FunctionalInterface注释的约束。
1、@FunctionalInterface注释的约束:
1、接口有且只能有个一个抽象方法,只有方法定义,没有方法体。
2、在接口中覆写Object类中的public方法,不算是函数式接口的方法。
2、函数式接口 示例:
下面三个接口都是函数式接口
接口一
@FunctionalInterface
public interface FunctionInterfaceTest {
String getInfo(String input);
@Override
String toString(); //Object中的方法
@Override
boolean equals(Object obj); //Object中的方法
}
接口二
@FunctionalInterface
public interface FunctionInterfaceTest {
String getInfo(String input);
}
接口三
public interface FunctionInterfaceTest {
String getInfo(String input);
}
3、函数式接口实例的创建
函数式接口实例的创建有三种方式:
1、lambda表达式;
2、方法引用;
3、构造方法引用。
1、代码示例
public class Main {
public static void main(String[] args) {
/**
* 1、lambda表达式
* 这种形式最为直观,lambda表达式,接收一个String类型的参数,返回一个String类型的结果。
* 完全符合函数式接口FunctionInterfaceTest的定义
*/
FunctionInterfaceTest functionInterfaceTest1 = item -> item+1;
/**
* 2、方法引用
* Main方法当中的getInstance和getMessage方法接收一个参数,返回一个结果。符合函数式接口
* FunctionInterfaceTest的定义。
* 函数式接口只是定义了个方法的约定(接收一个String类型的参数,返回一个String类型的结果),
* 而对于方法内部进行何种操作则并没有做任何的限制。在这点上,跟java以前的版本中的实现类与接口之间的
* 关系很类似。不同的是,函数式接口更偏重于计算过程,约束了一个计算过程的输入和输出。
* 这种约束计算过程的输入和输出的形式的好处可以看一下joinStr方法。
*/
FunctionInterfaceTest functionInterfaceTest2 = Main::getInstance; //方法引用
FunctionInterfaceTest functionInterfaceTest3 = Main::getMessage; //方法引用
String msg1 = joinStr("你好",functionInterfaceTest2); //输出:你好!世界
String msg2 = joinStr("你好",functionInterfaceTest3); //输出:世界,你好!
System.out.println(msg1);
System.out.println(msg2);
//还有更简单的写法,高度抽象化,具体处理由使用者自己决定
String msg3 = joinStr("你好",item ->item+"!世界"); //输出:你好!世界
String msg4 = joinStr("你好",item ->"世界,"+ item+"!"); //输出:世界,你好!
System.out.println(msg3);
System.out.println(msg4);
/**
* 3、构造方法引用
* 构造函数的结构:接收输入参数,然后返回一个对象。这种约束跟函数式接口的约束很像。
* 所以只要“输入参数类型”与“输出参数类型”跟FunctionInterfaceTest中的方法约束相同,
* 就可以创建出FunctionInterfaceTest接口的实例,如下,String的构造方法中有
* new String(str)的构造方法,所以可以得到实例。
* 这里存在一个类型推断的问题,JDK的编译器已经帮我们自动找到了只有一个参数,且是String类型的构造方法。
* 这就是我们直接String::new,没有指定使用哪一个构造方法,却可以创建实例的原因
*/
FunctionInterfaceTest functionInterfaceTest4 = String::new; //方法引用
}
public static String getInstance(String item){
return item+"!世界";
}
public static String getMessage(String massage){
return "世界,"+ massage+"!";
}
public static String joinStr(String str,FunctionInterfaceTest functionTest){
return functionTest.getInfo(str);
}
2、java8中常用的函数式接口:
接口 | 参数 | 返回类型 | 描述 |
---|---|---|---|
Predicate<T> | T | boolean | 用于判别一个对象。比如求一个人是否为男性 |
Consumer<T> | T | void | 用于接收一个对象进行处理但没有返回,比如接收一个人并打印他的名字 |
Function<T, R> | T | R | 转换一个对象为不同类型的对象 |
Supplier<T> | None | T | 提供一个对象 |
UnaryOperator<T> | T | T | 接收对象并返回同类型的对象,一般用于对对象属性修改。 |
BinaryOperator<T> | (T, T) | T | 接收两个同类型的对象,并返回一个原类型对象。可以理解为合并对象 |
常用的函数式接口主要有四种类型,是通过其输入和输出的参数来进行区分的。定义了编码过程中主要的使用场景。
Function<T,R>
接收一个T类型的参数,返回一个R类型的结果
接口中抽象的方法 :
R apply(T t);
Consumer<T>
接收一个T类型的参数,不返回值
接口中抽象的方法 :
void accept(T t);
Predicate<T>
接收一个T类型的参数,返回一个boolean类型的结果
接口中抽象的方法 :
boolean test(T t);
Supplier<T>
不接收参数,返回一个T类型的结果.
接口中抽象的方法 :
T get();
代码示例
public class FunctionalInterfaceMain {
public static void main(String[] args) {
/**
* 先看看如何创建它们
*/
Function<String,String> function1 = item -> item +"返回值";
Consumer<String> function2 = iterm -> {System.out.println(iterm);};
//lambda语句,使用大括号,没有return关键字,表示没有返回值
Predicate<String> function3 = iterm -> "".equals(iterm);
Supplier<String> function4 = () -> new String("");
/**
* 再看看怎么使用
* demo释义:
* 1、创建一个String类型的集合
* 2、将集合中的所有元素的末尾追加字符串'1'
* 3、选出长度大于2的字符串
* 4、遍历输出所有元素
*/
List<String> list = Arrays.asList("zhangsan","lisi","wangwu","xiaoming","zhaoliu");
list.stream()
.map(value -> value + "1") //传入的是一个Function函数式接口
.filter(value -> value.length() > 2) //传入的是一个Predicate函数式接口
.forEach(value -> System.out.println(value)); //传入的是一个Consumer函数式接口
}
}
3、接收两个参数的函数式接口
在实际使用中,我们往往会输入多个参数,而不是一个参数。针对于多个参数的计算,最终都可以拆分两个参数的运算,然后将两个参数的运算结合起来。如:1+2+3+4 = 10,可以拆分为1+2 = 3, 3+3=6; 6+4 = 10 三个步骤完成(在java中,是不允许一次返回多个值的)。
因此对于多个参数的操作也是如此。Java8中对于接收两个参数的场景提供了相关的函数式接口。如下:
BiFunction<T, U, R>
接收T类型和U类型的两个参数,返回一个R类型的结果。
接口中抽象的方法 :
R apply(T t, U u);
BiConsumer<T , U>
接收T类型和U类型的两个参数,不返回值。
接口中抽象的方法 :
void accept(T t, U u);
BiPredicate<T, U>
接收T类型和U类型的两个参数,返回一个boolean类型的结果。
接口中抽象的方法 :
boolean test(T t, U u);
代码示例
public class FunctionalInterfaceTest {
public static void main(String[] args) {
/**
* Bi类型的接口创建
*/
BiFunction<String, String, Integer> biFunction = (str1,str2) -> str1.length()+str2.length();
BiConsumer<String, String> biConsumer = (str1,str2) -> System.out.println(str1+str2);
BiPredicate<String, String> biPredicate = (str1,str2) -> str1.length() > str2.length();
/**
* Bi类型的接口使用
*/
int length = getLength("hello", "world", (str1,str2) -> str1.length() + str2.length()); //输出10
boolean boolean1 = getBoolean("hello", "world", (str1,str2) -> str1.length() > str2.length()); //输出false
System.out.println(length);
System.out.println(boolean1);
noResult("hello", "world", (str1,str2) -> System.out.println(str1+" "+str2)); //没有输出
}
public static int getLength(String str1,String str2,BiFunction<String, String, Integer> function){
return function.apply(str1, str2);
}
public static void noResult(String str1,String str2,BiConsumer<String, String> biConcumer){
biConcumer.accept(str1, str2);
}
public static boolean getBoolean(String str1,String str2,BiPredicate<String, String> biPredicate){
return biPredicate.test(str1, str2);
}
}
关于多个参数值的使用,无论是在Function接口中,还是在BI类型的接口都提供了类似的操作。(注:java8中,接口的方法是可以有实现的,但需要default关键字修饰,这是其他版本的jdk没有的特性)
4、Function接口的andThen方法和compose方法
源码:
default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
Objects.requireNonNull(before);
return (V v) -> apply(before.apply(v));
}
default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {
Objects.requireNonNull(after);
return (T t) -> after.apply(apply(t));
}
说明:
Compose方法:方法接收一个Function类型的参数,返回一个值。这也是一个标准的Function类型的定义。在compose方法内部也有一个apply方法。在执行compose方法中的apply方法之前,它先执行了before接口的apply方法,也是compose方法的输入参数。然后将before方法执行的返回值作为compose中apply方法的输入参数。实际上是形成了一种链式组合。
andThen方法:该方法与compose方法很类似。不同之处在于,andThen是先执行自身的apply方法,将apply的返回值作为after接口的输入值。相对于compose方法,只是方向的不同
使用:
public class FunctionalInterfaceTest {
public static void main(String[] args) {
String str1 = getLength1("hello", value -> "hello的长度:"+value, value -> value.length()); //输出:hello的长度:5
System.out.println(str1);
Integer result = getLength2("hello", value -> value, value -> value.length()); //输出:5
System.out.println(result);
}
public static String getLength1(String str1,Function<Integer, String> function1,Function<String,Integer> function2){
/**
* 这里一定要注意,function1和function2的参数类型。
* function2的输出类型与function1的输入类型一定要一致,
* 否则编译不会通过
*/
return function1.compose(function2).apply(str1);
}
public static Integer getLength2(String str1,Function<String, String> function1,Function<String,Integer> function2){
/**
* 这里一定要注意,function1和function2的参数类型。
* function1的输出类型与function2的输入类型一定要一致,(方向相反)
* 否则编译不会通过
*/
return function1.andThen(function2).apply(str1);
}
}
相关接口:BiFunction
public static Integer getLength3(String str1,String str2,BiFunction<String, String, String> biFunction,Function<String,Integer> function){
/**
* biFunction只有andThen方法,这是有bi类型接口的特征决定的。
* bi类型的接口需要接收两个参数,然而java中是没有返回两个参数的情况的
* 所以只有andThen方法,且其参数是function类型的,接收的是一个参数,
* 返回一个值
*/
return biFunction.andThen(function).apply(str1, str2);
}
5、Consumer接口的andThen方法
源码:
default Consumer<T> andThen(Consumer<? super T> after) {
Objects.requireNonNull(after);
return (T t) -> { accept(t); after.accept(t); };
}
说明:
将输入参数分别赋给andThen内部的accept方法和after内部的accept方法。After的计算在andThen之后,起到了后置连接的作用。在这里没有compose方法,因为后置连接反过来就是前置连接,所以不需要一个多余的compose方法了。只需要在传递时,交换两个consumer的顺序即可。
使用:
public class FunctionalInterfaceTest {
public static void main(String[] args) {
noResult(Integer.valueOf(12),
value -> {int num = value + 12;System.out.println(num);},
value -> { int num = value + 24;System.out.println(num);}
); //输出:24,36
}
public static void noResult(Integer num,Consumer<Integer> consumer1,Consumer<Integer> consumer2){
/**
* 两个consumer的接收类型必须一致
*/
consumer1.andThen(consumer2).accept(num);
}
}
相关接口:BiConsumer
public static void noResultBi(Integer num1,Integer num2,BiConsumer<Integer,Integer> consumer1,BiConsumer<Integer,Integer> consumer2){
/**
* 两个consumer的接收类型必须一致
*/
consumer1.andThen(consumer2).accept(num1,num2);
}
6、predicate接口的and、or、negate方法
源码:
default Predicate<T> and(Predicate<? super T> other) {
Objects.requireNonNull(other);
return (t) -> test(t) && other.test(t);
}
default Predicate<T> negate() {
return (t) -> !test(t);
}
default Predicate<T> or(Predicate<? super T> other) {
Objects.requireNonNull(other);
return (t) -> test(t) || other.test(t);
}
说明:
源码已经很清晰了,就不一一说明了。分别是&&, || 和取反操作。
使用:
public class FunctionalInterfaceTest {
public static void main(String[] args) {
getBoolean("hello", value -> value.length() > 2, value -> value.length() > 6);
}
public static boolean getBoolean(String str1,Predicate< String> predicate1,Predicate< String> predicate2){
boolean test = predicate1.or(predicate2).test(str1);
System.out.println(test); //输出true
test = predicate1.and(predicate2).test(str1);
System.out.println(test);//输出false
test = predicate1.negate().test(str1);
System.out.println(test);//输出false
return test;
}
}
相关接口:BiPreditcate
public static boolean getBooleanBi(String str1,String str2,BiPredicate<String, String> biPredicate1,BiP时redicate1.and(biPredicate2).test(str1, str2);
test = biPredicate1.negate().test(str1, str2);
test = biPredicate1.or(biPredicate2).test(str1, str2);
return test;
}
此外,java8针对原生类型int,long,double都提供了相应的函数式接口。如:DoubleConsumer, DoubleFunction,IntConsumer等等,使用方式都相同,见java.util.function包。