当前位置:   article > 正文

【Java8新特性】二、函数式接口

【Java8新特性】二、函数式接口

一、什么是函数式接口

  • 只包含一个抽象方法的接口,称为函数式接口。
  • 你可以通过 Lambda 表达式来创建该接口的对象。
  • 我们可以在任意函数式接口上使用 @FunctionalInterface 注解,这样做可以检查它是否是一个函数式接口,同时 javadoc 也会包含一条声明,说明这个接口是一个函数式接口

二、自定义函数式接口

@FunctionalInterface
public interface MyFunction {
    public String getValue(String str);
}

@FunctionalInterface
public interface MyFunc<T> {
    public R getValue(T t);
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

三、作为参数传递 Lambda 表达式

@FunctionalInterface
public interface MyFunc<T> {
    public T getValue(T t);
}

public String toUpperString(MyFunc<String> mf, String str) {
	mf.getValue(str)
}

//Lambda 表达式作为参数传递
String str1 = toUpperString(str -> str.toUpperCase(),"abcd");
sout(str1 )
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

四、四大内置核心函数式接口

在这里插入图片描述

1、消费形接口

    //Consumer: 消费型接口
    @Test
    public void test1(){
        happy(35,d -> System.out.println("花费了"+d));
    }

    public void happy(double money, Consumer<Double> con){
        con.accept(money);
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

2、供给形接口

    @Test
    public void test2(){
        List<Integer> numberList = getNumberList(10, () -> (int) (Math.random() * 100));

        for(Integer num : numberList){
            System.out.println(num);
        }
    }

    //需求:产生一些整数,并放在集合中
    public List<Integer> getNumberList(int num, Supplier<Integer> sup){
        List<Integer> list = new ArrayList<>();
        for(int i = 0; i < num ; i++){
             list.add(sup.get());
        }
        return list;
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

3、函数型接口

    @Test
    public void test3(){
        String result = Strandler("\t\thello world,i like china!", str -> str.trim());
        System.out.println(result);
    }

    //需求:用于处理字符串
    public String Strandler(String str, Function<String,String> fun){
        return fun.apply(str);
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

4、断言形接口

 @Test
    public void test4(){
        List<String> employees = Arrays.asList("hello","houchen","shuchenxi");
        List<String> list = filterStr(employees, str -> str.length() >3);
        for(String s : list){
            System.out.println(s);
        }
    }

    //需求:将满足条件的字符串放入集合中
    public List<String> filterStr(List<String> list, Predicate<String> pre){
        List<String> stringList = new ArrayList<>();

        for(String str : list){
            if(pre.test(str)){
                stringList.add(str);
            }
        }

        return stringList;
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/菜鸟追梦旅行/article/detail/411621
推荐阅读
相关标签
  

闽ICP备14008679号