zl程序教程

您现在的位置是:首页 >  后端

当前栏目

java 8 新特性3-函数式接口

JAVA接口 函数 特性
2023-09-27 14:22:13 时间

一 函数式接口

1.1 函数式接口

一个有且仅有一个抽象方法,但是可以有多个非抽象方法的接口。建议在接口上方加上关键字@FunctionalInterface

案例:

1.接口

package function;
@FunctionalInterface
public interface MyFriends {
    public void sayMessage(String name);
}

2.实现类

public class TestFriends {
    public static void main(String[] args) {
        //匿名内部类
        test("bj", new MyFriends() {
            @Override
            public void sayMessage(String name) {
                System.out.println("你好:"+name);
            }
        });
        //表达式2
        MyFriends myFriends=(x)->{ System.out.println("你好:"+x);};
        myFriends.sayMessage("bj");
        //lamda表达式
        test("bj",(x)->{ System.out.println("你好:"+x);});
    }
    public static void test(String name,MyFriends my){
        my.sayMessage(name);
    }
}

二 java8 提供的常用4个函数式接口

 

2.1 生产型接口

Supplier<T>接口也被称为生产型接口,如果我们指定了接口的泛型是什么类型,那么接口中的get方法就会生产什么类型的数据供我们使用。

生产型接口即:不用传参,但会返回一个参数 (01)。

public class TestPJiekou {
    public static void main(String[] args) {
     String s=getToUpper(()->{return "hello";});
     System.out.println("s:"+s);
    }
    public static String   getToUpper(Supplier<String> sup){
      return sup.get();
    }
}

 2.2 消费型接口

Consumer<T>接口也被称为消费型接口,它消费的数据的数据类型由泛型指定

生产型接口即:用传参,不返回值 (10)。

public class TestCJiekou {
    public static void main(String[] args) {
        consumerData("nihao",(x)->{System.out.println("x:"+x);});
        consumerData("nihao",(x)->{ System.out.println("t:"+x.toUpperCase());;},(x)->{System.out.println("x:"+x);});
    }
    public static void consumerData(String name, Consumer<String> con){
        con.accept(name);
    }
    public static void consumerData(String name,Consumer<String> con1,Consumer<String> con2){
        con1.andThen(con2).accept(name);
    }
}

2.3 判断性接口

Predicate<T>接口通常用于判断参数是否满足指定的条件 。

判断型接口即:参数无限制,必须有返回值 (x1)。 

public class TestPre {
    public static void main(String[] args) {
      boolean flag=check("ljf4",(x)->{return x.length()>3;});
      System.out.println("flag:"+flag);
    }
    public static boolean check(String s, Predicate<String> pre){
     return  pre.test(s);
    }
}

 2.4 funcation接口

Function<T,R>接口通常用于对参数进行处理,转换(处理逻辑由Lambda表达式实现),然后返回一个新的值 。

function接口即:有参数值,有返回值 (1,1)。 

代码:

public class TestFunction {
    public static void main(String[] args) {
        int k= res("ljf",(x)->{return x.length();});
        System.out.println("k:"+k);
    }
    public static Integer res(String name, Function<String,Integer> fun1){
       return  fun1.apply(name);
    }
}