java advanced: functional interface

1 what is a functional interface

                                

2 how to judge whether a functional interface is successfully created: use the function interface annotation (the same method as @ override)

                        ​​​​​​​        

3. Use of functional interfaces: generally, they can be used as method parameters and return values (review the knowledge of interface content here)

          1. If the method called by the main method and the parameter passed in by the method is an interface, you can:

                1. The parameters passed in the main method can be: the implementation class of the interface

                2 the parameters passed in the main method can be: the anonymous inner class of the interface

                 3 if the parameter in the method is a functional interface, you can use a lambda expression

package com.bed.hanshushijiekou;
//Three methods are used to call the abstract methods of the interface
public class mainfangfa {
    //The first way is to pass the interface directly and then invoke the method in the interface.
    public static void method1(myInterface myinter){
        myinter.method();
    }
    public static void main(String[] args) {
    //The second method: call method 1, and then pass the parameters to the implementation class of the interface
        method1(new myInterfaceimpl());
    //The third method. Parameter passes the anonymous inner class of the interface.
        method1(new myInterface() {
            @Override
            public void method() {
                System.out.println("An anonymous inner class that passes an interface overrides a method in the interface");
            }
        });
    //Similarly, the third method uses lambda expressions
        method1(()-> System.out.println("use lambda The anonymous inner class of the expression passing interface overrides the method in the interface"));
    }
}

                  Supplementary knowledge: lambda expressions can be regarded as the syntax sugar of anonymous inner classes. But lambda expressions are omitted

                                       The. class file is, so it is more efficient

         Add knowledge points: delay of lambda expression:

         The existing codes are as follows:

                                

          The log displays information only when the incoming level is level 1. When the incoming level is other levels, the group of msg1+msg2+msg3

          Combined operation is redundant. At this time, we can use the delay characteristic of lambda expression to save resources. Avoid performance waste         Code implementation:

//Create an interface with an abstract class method
package com.bed.hanshushijiekou.demo01;

public interface msgplus {
    public abstract String msgplus();
}

//Execution log
package com.bed.hanshushijiekou.demo01;

public class RiZhishow {
    public static void msgshow(int level,msgplus msg){
        if(level==1){
            System.out.println(msg.msgplus());
        }
    }
    public static void main(String[] args) {
        String msg1="hello";
        String msg2="bed";
        String msg3="java";

        msgshow(2,()->{
            return msg1+msg2+msg3;//Override abstract methods in interfaces
        });
    }
}

      1. Use lambda expression as the parameter of the method: (in fact, the above method is a large demonstration framework, while the following method is

                The main method is equivalent to adding more detailed operation steps to the constructed large framework (implementation class of interface)

          If the method called by the main method and the parameter passed in by the method is an interface, you can:

                1. The parameters passed in the main method can be: the implementation class of the interface

                2 the parameters passed in the main method can be: the anonymous inner class of the interface

                 3 if the parameter in the method is a functional interface, you can use a lambda expression

        ​​​​​​​        ​​​​​​​        

Code implementation:

package com.bed.hanshushijiekou;

public class ThreadRunable {
    public static void startThread(Runnable r){//The parameter is the Runnable interface
        new Thread(r).start();//Turn on Multithreading
    }

    public static void main(String[] args) {
        //Method 1 passes anonymous inner class (old method)
        startThread(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName()+"->"+"Thread started");
            }
        });
        //Method 2 uses lambda expressions
        startThread(()->{
            System.out.println(Thread.currentThread().getName()+"->"+"Thread started");
        });
    }
}

  2. Use lambda expression as the return value of the method:

         If the main method calls a method whose return value is an interface, you can:

                1. You can directly return: the implementation class of the interface

                2. You can directly return: the anonymous inner class of the interface

                 3 if the return value is a functional interface, you can use a lambda expression

Case 3 uses a custom comparator to compare character groups

package com.bed.hanshushijiekou;

import java.util.Arrays;
import java.util.Comparator;

public class ComparatorReturn {
    //Because the Comparator is to be modified, the return value of the method is the new Comparator comparator interface
    //The method is called getComparator
    public static Comparator<String> getComparator(){
        //111 the return value is the anonymous inner class new Comparator (old method)
      /*  return new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                //Sort by string length in descending order
                return o2.length()-o1.length();
            }
        };
        //222 New method: because the Comparator interface is a functional interface, lambda expressions are used
        return (String o1, String o2)->{return o2.length()-o1.length();};
        //333lambda Expression simplification*/
        return (o1, o2)->o2.length()-o1.length();//Sort array length
    }

    public static void main(String[] args) {
        String[] arr={"aaa","bbbbb","c","dd"};
        Arrays.sort(arr,getComparator());//Sort the arr using our own defined method
        System.out.println(Arrays.toString(arr));
    }
}

Part II: common functional interfaces:

        1. Supplier interface: production interface. The type of generic parameter passed is the type of return value

        

package com.bed.hanshushijiekou;

import java.util.function.Supplier;

public class getSupplier {
    //Define a method whose parameter is the Supplier interface
    public static String getString(Supplier<String> sup){
        return sup.get();//Call the get method in the Supplier interface. The return value here is also of type String
    }

    public static void main(String[] args) {
       // The parameter is the interface. Directly use the lambda expression to override the get method in the Supplier to make its return value meet the above method (String type)

        String s = getString(() -> "bed");
        System.out.println(s);
    }
}

            Case: use the Supplier functional interface to obtain the maximum value of the array:

                 (in fact, the above method is a large demonstration framework, and the following main method is equivalent to a large framework built

                         (just add more detailed operation steps to the implementation class and lambda expression of the interface)

package com.bed.hanshushijiekou;

import java.util.function.Supplier;

public class SupplierGetMax {
    public static int getmax(Supplier<Integer> sup){
        return sup.get();
    }

    public static void main(String[] args) {
        int[] arr={1,677,66,1,5,56,-23};
        int mmax=getmax(()->{
            int max=arr[0];
            for (int i : arr) {
                if(i>max){
                    max=i;
                }
            }
            return max;//This is the return value of the sup.get method
        });
        System.out.println(mmax);
    }
}

                2. Consumer interface (consumer, consumer):

        ​​​​​​​        ​​​​​​​        

          Case, 1Consumer's get method: use Consumer to reverse the name

package com.bed.hanshushijiekou.ConsumerPratice;

import java.util.function.Consumer;

public class ConsumerPractice {
    public static void getReverse(String name, Consumer<String> con){
        con.accept(name);
    }

    public static void main(String[] args) {
        getReverse("baierdong",(String name)->{
            String rename=new StringBuffer(name).reverse().toString();
            System.out.println(rename);
        });
    }
}

           andthen method of case 2Consumer: (Baton operation)

                 Use Consumer to make characters uppercase and then lowercase

package com.bed.hanshushijiekou.ConsumerPratice;

import java.util.function.Consumer;

public class ConsumerAndThen {
    public static void upAndLow(String s, Consumer<String> con1,Consumer<String> con2){
        //First call the accept method with con1, and then call the accept method with con2
        con1.andThen(con2).accept(s);
    }

    public static void main(String[] args) {
        upAndLow("xiaobaitu",
           (s)->{//accept method of con1
               System.out.println(s.toUpperCase());
        }, (s)->{//accept method of con2
               System.out.println(s.toLowerCase());
                });
    }
}

   Case 3. andthen method of Consumer:

        ​​​​​​​        ​​​​​​​        

         Case focus: 1. Cut in two times, one is to separate the array, and the other is to separate by comma         

                          2. Note that after splitting by comma, it will become an array state, and the order of the preceding elements is [0] the second element

                            The order is [1]... And so on. See code for details.

package com.bed.hanshushijiekou.ConsumerPratice;

import java.util.function.Consumer;

public class FenZuXianShi {
    //First use this method to split the array into strings one by one
    public static void chaiFen(String[] main, Consumer<String> con1,Consumer<String> con2){
        for (String s : main) {
            con1.andThen(con2).accept(s);//In this step, operate on the split single array s
        }
    }

    public static void main(String[] args) {
        String[] nameage={"bed1,19","bed2,29","bed3,39"};
        chaiFen(nameage,
            (part)->{
            //Use [] to form a pair of name and age;
            String name=part.split(",")[0];//After separating by commas, take out the element at position [0], that is, name
            System.out.print("full name"+name+",");
                },
            (part)->{
            String age=part.split(",")[1]; //Separated by commas, take out the element at position [1], that is, age
            System.out.println("Age"+age+". ");
                });
    }
}

       2. Predict interface:

        ​​​​​​​        ​​​​​​​        ​​​​​​​        

          1. The first method of predict: and (& &)

        ​​​​​​​        ​​​​​​​        ​​​​​​​        

package com.bed.hanshushijiekou.predicate;

import java.util.function.Predicate;

public class CompareNum {
    public static boolean compare(String s, Predicate<String> pre1,Predicate<String> pre2){
        //Whether the PRE-1 and pre-2 conditions are met at the same time
        return pre1.and(pre2).test(s);//This statement is equal to pre1. Test (s) & & pre2. Test (s)
    }

    public static void main(String[] args) {
        String s="abcdef";
        boolean b=compare(s,
                (s1)->{
                    return s.contains("a");
                },
                (s1)->{
                    return s.length()>5;
                });
        System.out.println(b);
    }
}

             2. The second method of predict: or (|)

        

            3. The third method of predict: negate (!)

        ​​​​​​​        ​​​​​​​        

  Case 1 personnel screening:

//Filter to screen out women older than 35
package com.bed.hanshushijiekou.predicate;

import java.util.ArrayList;
import java.util.function.Predicate;

public class PersonFilter {
    public static ArrayList<String> filter(String[] s, Predicate<String> pre1,Predicate<String> pre2){
        //Create an array to receive the results
        ArrayList<String> fire=new ArrayList<>();
        for (String person : s) {//Filter each group of data in the array
            if(pre1.and(pre2).test(person)){//If both conditions are met at the same time
                fire.add(person);
            }
        }
        return fire;
    }

    public static void main(String[] args) {
        String[] person={"male,35","female,25","male,25","female,40"};
        ArrayList<String> fire=filter(person,
                (String p)->{
                    //Divide by comma to determine whether the gender is male
                    String sex = p.split(",")[0];
                    return sex.equals("female");
                },
                (String p)->{
                    //Divide by comma to determine whether the age is greater than 35 years old
                    String s = p.split(",")[1];
                    Integer i=new Integer(s);//Cast delimited strings
                    return i>=35;
                });
        for (String s : fire) {
            System.out.println(s);
        }
    }
}

3.Function interface: conversion interface. It eats grass and produces milk

                1. apply method in Function interface

        ​​​​​​​        

package com.bed.hanshushijiekou.Function;

import java.util.function.Function;

public class Function1 {
    public static void getInt(String str, Function<String,Integer> fun){
        Integer apply = fun.apply(str);
        System.out.println(apply);
    }

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

          1. andthen method in Function interface: used for combination operation (or understood as baton operation)

        ​​​​​​​        ​​​​​​​        ​​​​​​​        

 

package com.bed.hanshushijiekou.Function;

import java.util.function.Function;

//Implementation 1: first split the string (String to String)
// 2: Convert String to Integer type (String to Integer)
// 3: + 10 after transition (Integer to Integer)
public class FunctionAndthen {
    public static int getInt(String str, //Three conversion to three FUNCTION interfaces
                             Function<String,String> fun1,
                             Function<String,Integer> fun2,
                             Function<Integer,Integer> fun3){
       return fun1.andThen(fun2).andThen(fun3).apply(str);
    }

    public static void main(String[] args) {
        String str="bed,9";
        int age=getInt(str,
                (s)->{
                   return s.split(",")[1];//The result is still of type String
                },
                (stoi)->{//Baton operation from the previous Function
                    return Integer.parseInt(stoi);//Get Integer from String
                },
                (i)->{
                    return i+20;//Baton operation
                });
        System.out.println(age);
    }
}

 

Tags: Java Eclipse

Posted on Sat, 20 Nov 2021 13:14:19 -0500 by law