Java8 - Predicates 和 Function

2019-11-01  本文已影响0人  咪啊p

什么是Predicates

interface Predicate<T> { 
    public boolean test(T t);
}

因为它是个function interface,所以我们可以用Lambda表达式
比如,实现test函数:

public boolean test(String s){
    return s.length()>3;
}

==>
(String s) -> {
     return s.length()>3;
}

==>
s->(s.length()>3);
public static void main(String[] args) {
        Predicate<String> dicate2 = s-> s.length()>3;
        System.out.println(dicate2.test("er"));
        System.out.println(dicate2.test("erer"));
}

Predicates 联合判断

Predicates提供了联合判断的方法:

看看下面的代码

public static void main(String[] args) {
    
        int[] A = {0,6,9,13,20,50,100};
        Predicate<Integer> p1 = i-> i>10;
        
        Predicate<Integer> p2 = i-> i%2 == 0;
        
        System.out.println("greater than 10:");
        m1(p1, A);
        
        System.out.println("less than 10:");
        m1(p1.negate(), A);
        
        System.out.println("Even numbers:");
        m1(p2,A);
        
        System.out.println("greater than 10 or Even number:");
        m1(p1.or(p2), A);
        
        System.out.println("greater than 10 and Even number:");
        m1(p1.and(p2), A);
        
        
    }
    
    public static void m1(Predicate<Integer> p, int[] A) {
        for (int i:A) {
            if(p.test(i)) {
                System.out.println(i);
            }   
        }
        
    }

什么是Function

interface function(T,R) {
    public R apply(T t);
}

同样Function是个Functional interface,可以使用Lambda 表达式

public static void main(String[] args) {
    Function<String, Integer> function= s -> s.length();
    System.out.println (function.apply("abc"));
}

Function compose andThen方法

先看看两者的用法:

// compose 用法:
function1.compose(function2).apply("abc");
//andThen 用法:
function1.andThen(function2).apply("abc");

compose的规则是,先执行function2的apply方法,然后把这个执行结果作为function1的输入,再执行function1.apply方法
andThen的规则是,先执行function1的apply方法,然后把这个执行结果作为function2的输入,再执行function2.apply方法

    Function<Integer,Integer> function1 = i -> i*i;
    Function<Integer,Integer> function2 = i -> i*4;
        
    System.out.println(function1.compose(function2).apply(10));
    System.out.println(function1.andThen(function2).apply(10));

输出结果:1600和400

BiFunction

BiFunction的接口定义是:Interface BiFunction<T,U,R>,其中:

- R apply([T] t,U u)
- default <V> BiFunction<T,U,V> andThen(Function<? super R,? extends V> after)

Supplier

结果的供应者,定义: Interface Supplier<T>,其中:

只有一个方法:

T get()
上一篇 下一篇

猜你喜欢

热点阅读