JAVA study notes 12-functional interface

Functional interface

1. Basic concepts
An interface with one and only one abstract method
Functional interface, that is, an interface suitable for functional programming scenarios. The function in Java is Lambda as the embodiment of programming, so functional interface is an interface that can be applied to Lambda. Lambda in Java can derive smoothly only if there is one and only one abstract method in the interface.
Syntax format:
modifier interface interface name { public abstract return value type method name (optional parameter information); } @FunctionalInterface annotation function: Yes Check whether the interface is a functional interface 2. The use of functional interface can generally be used as method parameters and return values





public class Demo01 {
    
    
    //定义一个方法,参数适用函数是接口MyFunctionalInterface
    public static void show(MyFuncitionalInterface myInter){
    
    
        myInter.method();
    }

    public static void main(String[] args) {
    
    
        //调用show方法,方法的参数是一个接口,所以可以传递接口的实现类对象
        show(new MyFunctionalInterfaceImpl());
        //调用show方法,方法的参数是一个接口,所以我们可以传递接口的匿名内部类
        show(new MyFuncitionalInterface() {
    
    
            @Override
            public void method() {
    
    
                System.out.println("使用匿名内部类");
            }
        });
        //调用show方法,方法的参数是一个函数式接口,可以使用Lambda表达式
        show(()->{
    
    
            System.out.println("使用Lambda重写接口中的抽象方法");
        });
    }
}

3. Functional programming

public class Demo02 {
    
    
    public static void showLog(int level,MessageBuilder mb){
    
    
        if(level==1){
    
    
            System.out.println(mb.builderMessage());
        }
    }

    public static void main(String[] args) {
    
    
        String msg1="hello";
        String msg2="world";
        String msg3="Java";
        showLog(1,()->{
    
    
            return msg1+msg2+msg3;
        });
        showLog(2,()->{
    
    
            return msg1+msg2+msg3;
        });
    }
}

Using Lambda expression as a parameter is only to pass the parameters to the showLog method. Only
when the conditions are met, the builderMessage method in the MessageBuilder method will be called. If the conditions are not met, then the builderMessage method in the MessageBuilder method will not be executed, and there will be no performance Wasteful
use of Lambda as a parameter

public class Demo03 {
    
    
    public static void startThread(Runnable run){
    
    
        new Thread(run).start();
    }

    public static void main(String[] args) {
    
    
        startThread(new Runnable() {
    
    
            @Override
            public void run() {
    
    
                System.out.println(Thread.currentThread().getName());
            }
        });
        //Lambda表达式
        startThread(()->{
    
    
            System.out.println(Thread.currentThread().getName());
        });
    }
}

Use Lambda as the return value

public class Demo04 {
    
    
    public static Comparator<String> getComparator(){
    
    
        return(String o1,String o2)->{
    
    
            return o2.length()-o1.length();
        };
    }

    public static void main(String[] args) {
    
    
        String[] arr={
    
    "Kobe","James","Curry","Jordan"};
        Arrays.sort(arr,getComparator());
        System.out.println(Arrays.toString(arr));
    }
}

4. Commonly used functional interface
Supplier interface
T get(): used to obtain object data of a specified type of generic parameter

public class Demo05 {
    
    
    //定义一个方法,方法的参数传递Supplier<T>接口,泛型执行String.get方法返回一个String
    public static String getString(Supplier<String> sup){
    
    
        return sup.get();
    }

    public static void main(String[] args) {
    
    
        //调用getString方法,方法的参数Supplier是一个函数式接口,所以可以传递Lambda表达式
        String s=getString(()->{
    
    
            return "hello,world";
        });
        System.out.println(s);
    }
}

Consumer interface
Abstract method: void accept(T t), which means to consume a specified generic data

public class Demo06 {
    
    
    public static void method(String s, Consumer<String> con){
    
    
        con.accept(s);
    }

    public static void main(String[] args) {
    
    
        //调用method方法,传递字符串,方法的另一个参数是Consumer接口,是一个函数式接口,可以使用Lambda表达式
        method("Kobe",(String s)->{
    
    
            System.out.println(s);
        });
    }
}

Default method: andThen If the parameters and return value of a method are all of the Consumer type, then the effect can be achieved: when consuming data, first do an operation, and then do an operation to achieve combination

public class Demo06 {
    
    
    //定义一个方法,方法的参数传递一个字符串和两个Consumer接口,Consumer接口的泛型使用字符串
    public static void method(String s,Consumer<String> con1,Consumer<String> con2){
    
    
/*        con1.accept(s);
        con2.accept(s);不使用andThen*/
        con1.andThen(con2).accept(s);
    }

    public static void main(String[] args) {
    
    
        method("hello",(t)->{
    
    
            System.out.println(t.toUpperCase());
        },(t)->{
    
    
            t.toLowerCase();
        });
    }  
}

Predicate interface
Judging a certain type of data
Abstract method: boolean test(T t)

public class Demo06 {
    
    
    public static boolean method(int num, Predicate<Integer> pre){
    
    
        return pre.test(num);
    }

    public static void main(String[] args) {
    
    
        int num=20;
        boolean res = method(num, (Integer n) -> {
    
    
            return n>10;
        });
        System.out.println(res);
    }
}

The default method and, or, negate

public class Demo06 {
    
    
    /*
    判断字符串长度是否大于5,字符串中是否包含a
     */
    public static boolean method(String s,Predicate<String> pre1,Predicate<String> pre2){
    
    
        return pre1.and(pre2).test(s);
        //return pre1.or(pre2).test(s);
    }

    public static void main(String[] args) {
    
    
        String s="HelloWorld";
        boolean res = method(s, (String str) -> {
    
    
            return str.length() > 5;
        }, (String str) -> {
    
    
            return str.contains("a");
        });
        System.out.println(res);
    }
}

Exercise

public class Demo07 {
    
    
    public static ArrayList<String> method(String[] arr, Predicate<String> pre1,Predicate<String> pre2){
    
    
        ArrayList<String> list=new ArrayList<>();
        for (String s : arr) {
    
    
            boolean b = pre1.and(pre2).test(s);
            if(b){
    
    
                list.add(s);
            }
        }
        return list;
    }

    public static void main(String[] args) {
    
    
        String[] arr={
    
    "Kobe,24","James,23","Jordan,23","Curry,30"};
        ArrayList<String> list = method(arr, (String s) -> {
    
    
            return s.split(",")[1].equals("23");
        }, (String s) -> {
    
    
            return s.split(",")[0].length() > 5;
        });
        System.out.println(list);
    }
}

Function interface
Interface is used to get data of one type according to another type.
Abstract method: R apply(T t), get the result of type R according to the parameter of T

public class Demo08 {
    
    
    public static void method(String s, Function<String,Integer> fun){
    
    
        Integer in=fun.apply(s);
        System.out.println(in);
    }

    public static void main(String[] args) {
    
    
        String s="12345";
        method(s,(String str)->{
    
    
            return Integer.parseInt(str);
        });
    }
}

Guess you like

Origin blog.csdn.net/qq_44708714/article/details/107161595