上一篇博客中Java8函數(shù)式編程之三:函數(shù)式接口 - 簡(jiǎn)書?留下的問題是關(guān)于Consumer接口的,本篇博客就來介紹一下Java8提供的重要的函數(shù)式接口募判。
1.Consumer接口:
我們首先看一下Consumer接口的Javadoc荡含,比任何資料都正規(guī)的解釋吝羞。
'
/**
* Represents an operation that accepts a single input argument and returns no
* result. Unlike most other functional interfaces, {@codeConsumer} is expected
* to operate via side-effects.
*/
@FunctionalInterface
public interfaceConsumer {
/**
* Performs this operation on the given argument. 通過給定的參數(shù)執(zhí)行操作
*/
voidaccept(Tt);
/**
* Returns a composed {@codeConsumer} that performs, in sequence, this
* operation followed by the {@codeafter} operation. If performing either
* operation throws an exception, it is relayed to the caller of the
* composed operation.? If performing this operation throws an exception,
* the {@codeafter} operation will not be performed.
*/
defaultConsumer andThen(Consumer after) {
Objects.requireNonNull(after);
return(Tt) -> { accept(t);after.accept(t); };
}
}
'
Consumer接口中定義了一個(gè)accept()的抽象方法,它接收泛型T的對(duì)象内颗,沒有返回(void).
一句話解釋就是:接收一個(gè)輸入?yún)?shù),不返回結(jié)果敦腔。
——————————————————————————————————
2.Function接口 :
/**
* Represents a function that accepts one argument and produces a result.
*/
@FunctionalInterface
public interfaceFunction {
/**
* Applies this function to the given argument.
*/
Rapply(Tt);
/**
* Returns a composed function that first applies the {@codebefore}
* function to its input, and then applies this function to the result.
* If evaluation of either function throws an exception, it is relayed to
* the caller of the composed function.
*/
default Function compose(Function before) {
Objects.requireNonNull(before);
return(Vv) -> apply(before.apply(v));
}
/**
* Returns a composed function that first applies this function to
* its input, and then applies the {@codeafter} function to the result.
* If evaluation of either function throws an exception, it is relayed to
* the caller of the composed function.
*/
default Function andThen(Function after) {
Objects.requireNonNull(after);
return(Tt) ->after.apply(apply(t));
}
/**
* Returns a function that always returns its input argument.
*
*@paramthe type of the input and output objects to the function
*@returna function that always returns its input argument
*/
static Function identity() {
returnt -> t;
}
}
Function接口定義了一個(gè)apply()方法均澳,它接收一個(gè)泛型T的對(duì)象,并返回一個(gè)R對(duì)象符衔。
一句話解釋就是:輸入一個(gè)參數(shù)找前,返回一個(gè)結(jié)果。
——————————————————
Function接口實(shí)例:
public classFunctionTest {
public static voidmain(String[] args) {
FunctionTest test =newFunctionTest();
//現(xiàn)在相當(dāng)于傳遞了一個(gè)行為/動(dòng)作給compute
System.out.print(test.compute(2, value -> {
return2* value;
}));
System.out.print(test.compute(5, value -> {
returnvalue +7;
}));
}
//一個(gè)計(jì)算函數(shù)
public intcompute(inta, Function function) {
returnfunction.apply(a);
}
}
————————————————————————————————————
3.BiFunction函數(shù)式接口:
/**
* Represents a function that accepts two arguments and produces a result.
* This is the two-arity specialization of {@linkFunction}.
*
*
This is afunctional interface
* whose functional method is {@link#apply(Object, Object)}.
*/
@FunctionalInterface
public interfaceBiFunction {
/**
* Applies this function to the given arguments.
*/
Rapply(Tt,Uu);
/**
* Returns a composed function that first applies this function to
* its input, and then applies the {@codeafter} function to the result.
* If evaluation of either function throws an exception, it is relayed to
* the caller of the composed function.
*/
default BiFunction andThen(Function after) {
Objects.requireNonNull(after);
return(Tt,Uu) ->after.apply(apply(t, u));
}
}
一句話總結(jié)就是:接收兩個(gè)參數(shù)判族,得到一個(gè)結(jié)果躺盛。
——————
Bifunction實(shí)例:
public classBiFunctionTest {
public static voidmain(String[] atgs) {
BiFunctionTest test =newBiFunctionTest();
System.out.print(test.compute(1,3, (value1, value2) -> value1 + value2));
System.out.print(test.compute(1,3, (value1, value2) -> value1 - value2));
//
System.out.print(test.compute2(3,2, (value1, value2) -> value1 + value2, value -> value - value));
}
public intcompute(inta,intb, BiFunction biFunction) {
returnbiFunction.apply(a, b);
}
//使用andThen
public intcompute2(inta,intb, BiFunction biFunction, Function function) {
returnbiFunction.andThen(function).apply(a, b);
}
}
————————————————————————
4.Predicate函數(shù)式接口:
/**
* Represents a predicate (boolean-valued function) of one argument.
*
*
This is afunctional interface
* whose functional method is {@link#test(Object)}.
*
*@paramthe type of the input to the predicate
*
*@since1.8
*/
@FunctionalInterface
public interfacePredicate {
/**
* Evaluates this predicate on the given argument.
*/
booleantest(Tt);
/**
* Returns a composed predicate that represents a short-circuiting logical
* AND of this predicate and another.? When evaluating the composed
* predicate, if this predicate is {@codefalse}, then the {@codeother}
* predicate is not evaluated.
*/
defaultPredicate and(Predicate other) {
Objects.requireNonNull(other);
return(t) -> test(t) &&other.test(t);
}
/**
* Returns a predicate that represents the logical negation of this
* predicate.
*/
defaultPredicate negate() {
return(t) -> !test(t);
}
/**
* Returns a composed predicate that represents a short-circuiting logical
* OR of this predicate and another.? When evaluating the composed
* predicate, if this predicate is {@codetrue}, then the {@codeother}
* predicate is not evaluated.
*/
defaultPredicate or(Predicate other) {
Objects.requireNonNull(other);
return(t) -> test(t) ||other.test(t);
}
/**
* Returns a predicate that tests if two arguments are equal according
* to {@linkObjects#equals(Object, Object)}.
*/
static Predicate isEqual(Object targetRef) {
return(null== targetRef)
? Objects::isNull
: object ->targetRef.equals(object);
}
}
一句話解釋就是:接收一個(gè)參數(shù),返回一個(gè)布爾值形帮。
Predicate接口里的其他方法:
1.邏輯與
defaultPredicate and(Predicate other) {
Objects.requireNonNull(other);
return(t) -> test(t) &&other.test(t);
}
2.邏輯非 (取反)
defaultPredicate negate() {
return(t) -> !test(t);
}
3.邏輯或
defaultPredicate or(Predicate other) {
Objects.requireNonNull(other);
return(t) -> test(t) ||other.test(t);
}
4.靜態(tài)方法槽惫,相等性/
static Predicate isEqual(Object targetRef) {
return(null== targetRef)
? Objects::isNull
: object ->targetRef.equals(object);
}
——————————
實(shí)例1:
public classPredicateTest {
public static voidmain(String[] args) {
List list = Arrays.asList(1,2,3,4,5,6,7,8,9);
PredicateTest test =newPredicateTest();
//找到集合中所有的奇數(shù)
test.conditionFilter(list, item -> item %2!=0);
//大于5的數(shù)
test.conditionFilter(list, item -> item >5);
//打印所有的元素
test.conditionFilter(list, item ->true);
//測(cè)試與
test.conditionFilter2(list, item -> item >5, item -> item %2==0);
//測(cè)試或
test.conditionFilter3(list, item -> item >5, item -> item %2==0);
//測(cè)試非
test.conditionFilter4(list, item -> item >5, item -> item %2==0);
//相等性判斷
System.out.print(test.isEqual("test").test("test"));
}
//函數(shù)式編程提供了一種更高層次的抽象
public voidconditionFilter(List list, Predicate predicate) {
for(Integer integer : list) {
if(predicate.test(integer)) {
System.out.print(integer +" ");
}
}
}
//與
public voidconditionFilter2(List list, Predicate predicate1, Predicate predicate2) {
for(Integer integer : list) {
if(predicate1.and(predicate2).test(integer)) {
System.out.print(integer);
}
}
}
//或
public voidconditionFilter3(List list, Predicate predicate1, Predicate predicate2) {
for(Integer integer : list) {
if(predicate1.or(predicate2).test(integer)) {
System.out.print(integer);
}
}
}
//非
public voidconditionFilter4(List list, Predicate predicate1, Predicate predicate2) {
for(Integer integer : list) {
if(predicate1.and(predicate2).negate().test(integer)) {
System.out.print(integer);
}
}
}
//想等性判斷
publicPredicate isEqual(Object object) {
returnPredicate.isEqual(object);
}
}
————————————————
5.Supplier函數(shù)式接口:
/**
* Represents a supplier of results.
*
*
There is no requirement that a new or distinct result be returned each
* time the supplier is invoked.
*
*
This is afunctional interface
* whose functional method is {@link#get()}.
*/
@FunctionalInterface
public interfaceSupplier {
/**
* Gets a result.
*/
Tget();
}
一句話解釋就是:不接收任何參數(shù),返回一個(gè)結(jié)果辩撑。
——————————————————————————
public classSupplierTest {
public static voidmain(String[] args){
//不接收參數(shù),返回一個(gè)結(jié)果
Supplier supplier = () ->"hello world";
System.out.print(supplier.get());
}
}
————————————
實(shí)例2:
public classStudent {
privateStringname="zhangsan";
private intage;
publicStudent(){
}
publicStudent(String name,intage){
this.name= name;
this.age= age;
}
publicString getName() {
returnname;
}
public voidsetName(String name) {
this.name= name;
}
public intgetAge() {
returnage;
}
public voidsetAge(intage) {
this.age= age;
}
}
——————————————
public classStudentTest {
public static voidmain(String[] args){
Supplier supplier = () ->newStudent();
System.out.print(supplier.get().getName());
//使用構(gòu)造方法引用
Supplier supplier1 = Student::new;
System.out.print(supplier1.get().getName());
}
}
————————————————
6.BinaryOperator函數(shù)式接口
/**
* Represents an operation upon two operands of the same type, producing a result
* of the same type as the operands.? This is a specialization of
* {@linkBiFunction} for the case where the operands and the result are all of
* the same type.
*
*
This is afunctional interface
* whose functional method is {@link#apply(Object, Object)}.
*/
@FunctionalInterface
public interfaceBinaryOperatorextendsBiFunction {
/**
* Returns a {@linkBinaryOperator} which returns the lesser of two elements
* according to the specified {@codeComparator}.
*/
public static BinaryOperator minBy(Comparator comparator) {
Objects.requireNonNull(comparator);
return(a, b) ->comparator.compare(a, b) <=0? a : b;
}
/**
* Returns a {@linkBinaryOperator} which returns the greater of two elements
* according to the specified {@codeComparator}.
*/
public static BinaryOperator maxBy(Comparator comparator) {
Objects.requireNonNull(comparator);
return(a, b) ->comparator.compare(a, b) >=0? a : b;
}
}
一句話解釋就是:接收兩個(gè)相同類型的參數(shù)界斜,返回一個(gè)結(jié)果。
————————————————
public classBinaryOperatorTest {
public static voidmain(String[] args){
BinaryOperatorTest test =newBinaryOperatorTest();
System.out.print(test.compute(1,2,(a,b) -> a +b));
}
public intcompute(inta,intb, BinaryOperator binaryOperator){
returnbinaryOperator.apply(a,b);
}
publicString getShort(String a, String b, Comparator comparator){
returnBinaryOperator.minBy(comparator).apply(a,b);
}
}
——————————————————————
6.Optinal函數(shù)式接口:
/**
* A container object which may or may not contain a non-null value.
* If a value is present, {@codeisPresent()} will return {@codetrue} and
* {@codeget()} will return the value.
*
*
Additional methods that depend on the presence or absence of a contained
* value are provided, such as {@link#orElse(java.lang.Object) orElse()}
* (return a default value if value not present) and
* {@link#ifPresent(java.util.function.Consumer) ifPresent()} (execute a block
* of code if the value is present).
*/
public final classOptional
一句話解釋就是:為了解決Java中的NPE問題(NullPointerExeception)
(程序員認(rèn)為某個(gè)對(duì)象不會(huì)為空合冀,而去使用這個(gè)對(duì)象調(diào)用某個(gè)方法各薇,導(dǎo)致出現(xiàn)NullPointerExeception)
————————————————
Optinal是一個(gè)容器對(duì)象,里面可以包含或者不包含一個(gè)非空值君躺。如果這個(gè)值存在峭判,isPresent()方法會(huì)返回true,get()方法會(huì)返回這個(gè)值棕叫。
——————
幾個(gè)工廠方法構(gòu)造對(duì)象
1.構(gòu)造一個(gè)值為null的對(duì)象
public static Optional empty() {
@SuppressWarnings("unchecked")
Optional t = (Optional)EMPTY;
returnt;
}
2.構(gòu)造一個(gè)不為null的對(duì)象
public static Optional of(Tvalue) {
return newOptional<>(value);
}
3.構(gòu)造出可能為null林螃,也可能不為null的對(duì)象
public static Optional ofNullable(Tvalue) {
returnvalue ==null?empty() :of(value);
}
————————————————————
4.取值get();
publicTget() {
if(value==null) {
throw newNoSuchElementException("No value present");
}
returnvalue;
}
5.判斷對(duì)象是否存在 isPresent()
public booleanisPresent() {
returnvalue!=null;
}
——————————————
public classOptionalTest {
public static voidmain(String[] args){
//不能new,需要用工廠方法創(chuàng)建
Optional optional = Optional.of("hello");
optional.ifPresent(item -> System.out.print(item));
//如果里面沒有值俺泣,就打出word
System.out.print(optional.orElse("world"));
}
}