您的位置:首页 > 编程语言 > Java开发

java8学习总结——函数式接口@FunctionalInterface

2017-12-10 12:14 746 查看
      Java8提倡函数式变成,因而新增了一个函数式接口。函数式接口保证了函数式编程,同时也保证了能够兼容以前的java版本。

 

     函数式接口的定义

     在java8中,满足下面任意一个条件的接口都是函数式接口:

1、被@FunctionalInterface注释的接口,满足@FunctionalInterface注释的约束。

2、没有被@FunctionalInterface注释的接口,但是满足@FunctionalInterface注释的约束

 

     @FunctionalInterface注释的约束:

1、接口有且只能有个一个抽象方法,只有方法定义,没有方法体

2、在接口中覆写Object类中的public方法,不算是函数式接口的方法。

下面三个接口都是函数式接口:

//接口一
@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);

}


      函数式接口实例的创建

函数式接口实例的创建有三种方式:1、lambda表达式;2、方法引用;3、构造方法引用。

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);
}

       java8中常用的函数式接口:

常用的函数式接口主要有四种类型,是通过其输入和输出的参数来进行区分的。定义了编码过程中主要的使用场景。

 接口名

   说明

  Function<T,R>   

  接收一个T类型的参数,返回一个R类型的结果

  Consumer<T>

  接收一个T类型的参数,不返回值

  Predicate<T>

  接收一个T类型的参数,返回一个boolean类型的结果

  Supplier<T>

  不接受参数,返回一个T类型的结果

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函数式接口
}

}


       在实际使用中,我们往往会输入多个参数,而不是一个参数。针对于多个参数的计算,最终都可以拆分两个参数的运算,然后将两个参数的运算结合起来。如:1+2+3+4 = 10,可以拆分为1+2 = 3,   3+3=6;   6+4 = 10 三个步骤完成(在java中,是不允许一次返回多个值的)。

      因此对于多个参数的操作也是如此。Java8中对于接收两个参数的场景提供了相关的函数式接口。如下:

接口名

   说明

BiFunction<T, U, R>   

   接收T类型和U类型的两个参数,返回一个R类型的结果

BiConsumer<T , U>

   接收T类型和U类型的两个参数,不返回值

BiPredicate<T, U>

   接收T类型和U类型的两个参数,返回一个boolean类
c55f
型的结果

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没有的特性)
1、  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);
}


2、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);
}

3、 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,BiPredicate<String, String> biPredicate2){
boolean test = biPredicate1.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包。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: