lambda的函数式接口

  函数式接口就是只包含一个抽象方法的接口A(不包括默认抽象方法,但包括继承来的方法);这个接口用来作为一个可变作用的方法B的参数。函数式接口的抽象方法的参数类型和返回值就是一套签名,这个签名叫做函数描述符,可以描述lambda的类型。@FunctionalInterface

   1.8给了几个用来描述常见函数描述符的函数式接口:Predicate、Consumer、Function

   1、Predicate

    Predicate接口定义了一个名为test的抽象方法,它接受泛型T的对象,返回一个boolean。就是传进来任意对象在方法中用来判断是否(断言)。

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

    public static<T> List<T> filter(List<T> list,Predicate<T> p){
        List<T> results= new ArrayList<>();
        for(T s:list){
            if(p.test(s)){
                results.add(s);
            }
        }
    return results;
    }   

Predicate<String> nonEmptyStringPredicate=(String s)->!s.isEmpty();
List<String> nonEmpty=filter(listOfStrings,nonEmptyPredicate);

     2、Consumer

    Consumer接口定义了一个accept()的方法,参数为一个泛型T,返回值为空;就是消费的意思,方法将传入的泛型对象进行某些操作处理就消费空了。

@FunctionalInterface
public interface Consumer<T>{
    void accept(T t);
}
   
public static <T> void forEach(List <T> list,Consumer<T> c){
    for(T i:list){
        c.accept(i);
    }
}

forEach(Arrays.asList(1,2,3,4,5),(Integer i)->System.out.println(i));

  

    3、function

    function接口定义了一个apply()的方法,它接受一个泛型T的对象,并返回一个泛型R的对象。通过该接口的抽象方法就可以将一种泛型经过一系列操作变为另一种泛型。

@FunctionalInterface
public interface Function<T,R>{
    R apply(T t);
}

public static<T,R> List<R> map(List<T> list,Function<T,R>  f){
    List<R> result = new ArrayList<>();
    for(T s:list){
        result.add(f.apply(s));
    }
    return result;
}

List<Integer> l=map(Arrays.aslist("lambdas","in","action"),(String s)->s.length());

猜你喜欢

转载自www.cnblogs.com/television/p/9274163.html
今日推荐