企业如何在自己的网站上做宣传,衡水大型网站建设,优秀app网站设计,微信微商城怎么进入JDK 1.8 API包含了很多内建的函数式接口#xff0c;在老Java中常用到的比如Comparator或者Runnable接口#xff0c;这些接口都增加了FunctionalInterface注解以便能用在lambda上。现如今#xff0c;我们则从Function常用函数入口#xff0c;真正了解一下。
nametypedescri…JDK 1.8 API包含了很多内建的函数式接口在老Java中常用到的比如Comparator或者Runnable接口这些接口都增加了FunctionalInterface注解以便能用在lambda上。现如今我们则从Function常用函数入口真正了解一下。
nametypedescriptionConsumerConsumer T 接收T对象不返回值PredicatePredicate T 接收T对象并返回booleanFunctionFunction T, R 接收T对象返回R对象SupplierSupplier T 提供T对象例如工厂不接收值UnaryOperatorUnaryOperator接收T对象返回T对象BinaryOperatorBinaryOperator接收两个T对象返回T对象
标注为FunctionalInterface的接口被称为函数式接口该接口只能有一个自定义方法但是可以包括从object类继承而来的方法。如果一个接口只有一个方法则编译器会认为这就是一个函数式接口。是否是一个函数式接口需要注意的有以下几点
该注解只能标记在”有且仅有一个抽象方法”的接口上。
JDK8接口中的静态方法和默认方法都不算是抽象方法。
接口默认继承java.lang.Object所以如果接口显示声明覆盖了Object中方法那么也不算抽象方法。 该注解不是必须的如果一个接口符合”函数式接口”定义那么加不加该注解都没有影响。加上该注解能够更好地让编译器进行检查。如果编写的不是函数式接口但是加上了FunctionInterface那么编译器会报错。 在一个接口中定义两个自定义的方法就会产生Invalid ‘FunctionalInterface’ annotation; FunctionalInterfaceTest is not a functional interface错误. Function常用方法实践
//将Function对象应用到输入的参数上然后返回计算结果。
R apply(T t);例子1先来个简单版的传String返回String。
package org.dreams.transaction;import java.util.function.Function;public class FunctionTestIn, Out {private FunctionIn, Out processor new FunctionIn, Out() {Overridepublic Out apply(In in) {return (Out) new String(apply: in);}};public static void main(String[] args) {FunctionTestString, String functionTest new FunctionTest();System.out.println(functionTest.processor.apply(hello~!));}
}
lambda表达式的写法package org.dreams.transaction;import java.util.function.Function;public class FunctionTestIn, Out {private FunctionIn, Out processor in - {return (Out) new String(apply: in);};public static void main(String[] args) {FunctionTestString, String functionTest new FunctionTest();System.out.println(functionTest.processor.apply(hello~!));}
}例子二 andThen方法
//返回一个先执行当前函数对象apply方法再执行after函数对象apply方法的函数对象。
default V FunctionT, V andThen(Function? super R, ? extends V after) {Objects.requireNonNull(after);return (T t) - after.apply(apply(t));}compose方法
//返回一个先执行before函数对象apply方法再执行当前函数对象apply方法的函数对象
default V FunctionV, R compose(Function? super V, ? extends T before) {Objects.requireNonNull(before);return (V v) - apply(before.apply(v));}完整代码
package org.dreams.transaction.java8;import java.util.function.Function;public class Function2Test{public static void main(String[] args) {FunctionInteger, Integer name e - e * 2;FunctionInteger, Integer square e - e * e;int value name.andThen(square).apply(3);System.out.println(andThen value value);int value2 name.compose(square).apply(3);System.out.println(compose value2 value2);//返回一个执行了apply()方法之后只会返回输入参数的函数对象Object identity Function.identity().apply(huohuo);System.out.println(identity);}
}返回结果
andThen value36
compose value218
huohuo