java8-lambda(3)内置的函数接口

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/answer100answer/article/details/87896377

1. java8内置的4大函数式接口

在使用函数式接口时,每次得先新建接口。可以直接使用java8的内置函数接口。
特点:函数式接口的实现,作为另外一个函数的参数使用。
Java8内置的四大核心函数式接口

  • Consumer<T>:消费型接口
    void accept(T t);
    //1.消费性 无返回结果
    @Test
    public void test1(){
        eat(100.00, m-> System.out.println("吃饭消费:"+m+"元"));//吃饭消费:100.0元
    }
    private void eat(double m, Consumer<Double> consumer){
        consumer.accept(m);
    }
  • Supplier<T>:供给型接口
    T get();
    //2.供给型 从无到有
    private List<Integer> getNumList(int n, Supplier<Integer> supplier){
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            Integer num = supplier.get();
            list.add(num);
        }
        return list;
    }
    //例如返回5个随机数
    @Test
    public void test2(){
        List<Integer> randomIntegerList = getNumList(5,()->(int)(Math.random()*100));
        System.out.println(randomIntegerList);  //[92, 77, 88, 26, 79]
    }
  • Function<T, R>:函数型接口
    R apply(T t);
    //3.函数式接口
    private String strHandle(String str, Function<String,String> fun){
        return fun.apply(str);
    }
    @Test
    public void test3(){
        String s = strHandle("Abab",x->x.toUpperCase());
        System.out.println(s); //ABAB
    }
  • Predicate<T>:断言型接口
    boolean test(T t);
    //4.断言式接口
    //将符合条件的strList过滤出来
    private List<String> filterList(List<String> str, Predicate<String> pre){
        List<String> list = new ArrayList<>();
        for (String s : str) {
            if(pre.test(s)){
                list.add(s);
            }
        }
        return list;
    }
    @Test
    public void test4(){
        List<String> str = Arrays.asList("hello","world","didi");
        List<String> filterRes = filterList(str,x->x.length()>4);
        System.out.println(filterRes); //[hello, world]
    }

2.扩展接口

使用方法同上。

猜你喜欢

转载自blog.csdn.net/answer100answer/article/details/87896377