Predicate接口(判断),Function接口(转换)

Predicate接口(判断接口):

有时候我们需要对某种类型的数据进行判断,从而得到一个boolean值结果。

这时可以使用java.util.function.Predicate接口。

抽象方法:test

test方法就是用来判断一个对象是否符合指定的规则

规则在Predicate接口对象指定,而由于该接口是函数式接口,

所以该规则可以在Lambda表达式中指定。

练习:

 

默认方法:and

作用:可以判断条件是否可以同时成立。

其实and 是个与 &&

既然是条件判断,就会存在与、或、非三种常见的逻辑关系。

其中将两个Predicate条件使用“与”逻辑连接起来实现“并且”的效果时,可以使用default方法and。其JDK源码为:

package com.luliang.Function.test;

import java.util.function.Predicate;

public class Demo01 {
    private static boolean lu(Predicate b) {
        boolean helloworld = b.test("Hello World");
        System.out.println("字符串的长度。" + helloworld);
        return helloworld;
    }
    public static void main(String[] args) {
         lu(s -> s.length() > 5);
    }
}

默认方法:or 其实是个或 ||

and的“与”类似,默认方法or实现逻辑关系中的“”。JDK源码为:

default Predicate or(Predicate other) {
    Objects.requireNonNull(other);
    return (t) -> test(t) || other.test(t);
}

默认方法:negate其实是个取反 !

Function接口(转换接口):

抽象方法:apply

R apply(T t),其实就是把T类型转换为R类型。

默认方法:andThen 方法.

'

 

 

 

 

 

 

 

 

 

 

 

你可能感兴趣的:(java)