【Java8新特性】——四种核心内置函数式接口详解

【前言】

前一篇讲解Lamda的如何使用以及使用的前提是函数式接口,本篇小编讲解一下Java8内置的四种函数式接口以及具体的使用方法。

【内容】

一:函数式接口有什么特点?
函数式接口只有一个方法,可以用注解@FunctionalInterface表示,当加上这个注解之后就给这个接口加上了条件,一旦接口中出现多个方法就会出现问题。
二:核心内置函数有哪些?

函数式接口 参数类型 返回类型 用途
Consumer T void 对类型T参数操作,无返回结果,包含方法 void accept(T t)
Supplier T 返回T类型参数,方法时 T get()
Function T R 对类型T参数操作,返回R类型参数,包含方法 R apply(T t)
Predicate T boolean 断言型接口,对类型T进行条件筛选操作,返回boolean,包含方法 boolean test(T t)

三:具体的使用:

/**
 * Java8内置的四大核心函数式接口:
 * Consumer<T>:消费型接口</T>
 *
 *
 * Supplier<T>供给型接口</T>
 *
 * Function<T,R>函数型接口</T,R>
 *
 *
 * Predicate<T>段言型接口</T>
 * boolean test(T t)
 */



public class TestLamda3 {

    //Consumer<T>

    @Test
    public void test1(){
        happy(10000,(m)-> System.out.println("这次消费了"+m+"元"));
    }

    public  void happy(double money, Consumer<Double> con){
        con.accept(money);
    }

    //Supplier<T>
    @Test
    public  void test2(){
     List<Integer> list=   getNumList(5,()->{
            return (int)Math.random()*100;
        });

     list.forEach(System.out::println);
    }

    public List<Integer> getNumList(int num, Supplier<Integer> supplier){
          List<Integer>  list=new ArrayList<>();
          for (int i=0; i<num;i++){
              Integer n=supplier.get();
              list.add(n);
          }

          return  list;
    }


    //函数式接口
    @Test
    public  void test4(){
         String newStr=strHandle("\t\t\t woshi nide ",(str)->str.trim());
         System.out.println(newStr);
    }

    public  String strHandle(String str,Function<String,String> fun){
     return fun.apply(str);
    }


    //段言型接口;将满足条件的字符串放入集合中

    @Test
    public void test5(){

        List<String> list1= Arrays.asList("nihao","hiehei","woai","ni");
      List<String> list=filterStr(list1,(s)->s.length()>3);
        for (String s : list) {
            System.out.println(s);
        }
    }

    public List<String>  filterStr(List<String> list, Predicate<String> pre){
        List<String> strings=new ArrayList<>();
        for (String string : list) {
            if(pre.test(string)){
                strings.add(string);
            }
        }
        return strings;

    }


}

其他延伸函数式接口:

函数式接口 参数类型 返回类型 用途
BigFunction T,U R 对类型T,参数操作,返回R类型结果,包含方法 R apply(T t,U u)
UnaryOperator:Function子接口 T T 对类型T对象进行一元运算,并且返回T类型的结果,包含方法 T apply(T t)
BinaryOperator T,T T 对类型T对象进行二元运算,并返回T类型的结果,包含方法T apply(T t1,T t2)
BigConsumer T,U void 对类型T,u参数进行操作,包含方法void accept(T t,U u)
ToIntFunction:ToLongFunction:ToDoubleFuction T int,long,double 分别计算int,long,double值得函数
IntFunction :LongFunction:DoubleFunction int,long,double R 参数分别是int,long,double类型函数

[总结]

函数式接口是为了lamda表达式服务,函数式接口的存在是Lamda表达式出现的前提,Lamda表达式想关于重写了函数式接口中的唯一方法。

猜你喜欢

转载自blog.csdn.net/changyinling520/article/details/80570103
今日推荐