UDP, TCP, Lambda expression, interface composition update, method reference

Posted by mooler on Sun, 20 Feb 2022 10:31:58 +0100

UDP communication principle: UDP protocol is an unreliable network protocol. It has a Socket object at both ends of the communication, but these two sockets are only the objects to send and receive data

Both sides of communication based on UDP protocol have no so-called concept of client and server

The datagram Socket class provided by Java is the Socket based on UDP protocol

UDP send data

To send data

1. Create the Socket object (DatagramSocket) of the sender

        DatagramSocket()

2. Create data and package it

        DatagramSocket(byte[] buf, int length,InetAddress address,int port)

3. Call the method of DatagramSocket object to send data

        void send(DatagramPacket p)

4. Close the sender

        void close()

public class Demo {
    public static void main(String[] args) throws IOException {
        DatagramSocket ds = new DatagramSocket();
        byte[] bys = "helloworld".getBytes();
//        int length = bys.length;
//        InetAddress m = Inet4Address.getByName("m");
//        int port = 10086;
//        DatagramPacket dp = new DatagramPacket(bys,length,m,port);
        DatagramPacket dp = new DatagramPacket(bys,bys.length,Inet4Address.getByName("m"),10086);
        //Send datagram packet
        ds.send(dp);
        ds.close();
    }
}

UDP receive data

Steps to receive data

1. Create the Socket object (DatagramSocket) of the receiving end

        DatagramSocket()

2. Create a packet for receiving data

Datagram packet (byte[] buf, int length) constructs a datagram packet for receiving data packets with length

3. Call the method of DatagramSocket object to receive data

void receive (datagram packet P) receives datagram packets from this socket

4. Analyze the data package and display the data on the console

byte[] getData() returns the data buffer.

int getLength() returns the length of data to be sent or received.

5. Close the receiver

        void close();

public class ReceiveDemo {
    public static void main(String[] args) throws IOException {
        DatagramSocket ds = new DatagramSocket(10086);
        //Datagram packet (byte[] buf, int length) constructs a datagram packet for receiving data packets with length.
        byte[] bys = new byte[1024];
        DatagramPacket dp = new DatagramPacket(bys,bys.length);
        //void receive (datagram packet P) receives datagram packets from this socket.
        ds.receive(dp);
        //byte[] getData() returns the data buffer.
//        byte[] data = dp.getData();
        //int getLength() returns the length of data to be sent or received.
//        int len  = dp.getLength();
//        String dataString = new String(data,0,len);
//        System.out.println(dataString);
        System.out.println(new String(dp.getData(),0,dp.getLength()));
        ds.close();
    }
}

UDP communication program exercise

public class ReceiveDemo {
    public static void main(String[] args) throws IOException {
        while (true){
            DatagramSocket ds = new DatagramSocket(10086);
            //Datagram packet (byte[] buf, int length) constructs a datagram packet for receiving data packets with length.
            byte[] bys = new byte[1024];
            DatagramPacket dp = new DatagramPacket(bys,bys.length);
            //void receive (datagram packet P) receives datagram packets from this socket.
            ds.receive(dp);
            System.out.println(new String(dp.getData(),0,dp.getLength()));
            ds.close();
        }


    }
}
public class Demo {
    public static void main(String[] args) throws IOException {
        DatagramSocket ds = new DatagramSocket();
        //Encapsulate the keyboard to enter data
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String line;
        while ((line = br.readLine())!=null){
            if ("886".equals(line)){
                break;
            }
            byte[] bys = line.getBytes();
            DatagramPacket dp = new DatagramPacket(bys,bys.length,Inet4Address.getByName("m"),10086);
            //Send datagram packet
            ds.send(dp);
        }
        ds.close();
    }
}

TCP communication principle

TCP communication protocol is a reliable network protocol. It establishes a Socket object at both ends of the communication, so as to form a network virtual link at both ends of the communication. Once the virtual network link is established, the programs at both ends can communicate through the virtual link

Java provides a good package for the network based on TCP protocol, uses Socket object to represent the communication ports at both ends, and generates IO flow through Socket for network communication

The Java bit client provides the Socket class, and the bit server provides the ServerSocket class

TCP send data

1. Create the client's Socket object (Socket)

Socket (InetAddress, int port) creates a stream socket and connects it to the specified port number of the specified IP address.

Socket (String host, int port) creates a stream socket and connects it to the specified port number on the specified host.

2. Obtain output stream and write data

OutputStream getOutputStream() returns the output stream of this socket.

3. Release resources

        void close();

    public static void main(String[] args) throws IOException {
        // Socket (InetAddress, int port) creates a stream socket and connects it to the specified port number of the specified IP address.
//        Socket s = new Socket(Inet4Address.getByName("m"),10086);
        //Socket (String host, int port) creates a stream socket and connects it to the specified port number on the specified host.
        Socket s = new Socket("m",10086);
        //Get output stream and write data
        //OutputStream getOutputStream() returns the output stream of this socket.
        OutputStream os  = s.getOutputStream();
        os.write("hello".getBytes());
        s.close();
    }

TCP receive data

1. Create a server-side Socket object (ServerSocket)

ServerSocket (int port) creates a server socket bound to a specified port.

2. Listen to the client connection and return a Socket object

Socket accept() listens for the socket to be connected to and accepts it.

3. Obtain the input stream, read the data, and display the data on the console

InputStream getInputStream() returns the input stream of this socket.

4. Release resources

        void close()

   public static void main(String[] args) throws IOException {
        //ServerSocket (int port) creates a server socket bound to a specified port.
        ServerSocket ss = new ServerSocket(10086);
        //Socket accept() listens for the socket to be connected to and accepts it.
        Socket s = ss.accept();
        //Get the input stream, read the data, and display the data on the console
        InputStream is = s.getInputStream();
        byte[] bys = new byte[1024];
        int len;
        while ((len = is.read(bys))!=-1){
            String data = new String(bys,0,len);
            System.out.println(data);
        }
        s.close();
        ss.close();
    }

TCP communication program exercise

    public static void main(String[] args) throws IOException {
        // Socket (InetAddress, int port) creates a stream socket and connects it to the specified port number of the specified IP address.
//        Socket s = new Socket(Inet4Address.getByName("m"),10086);
        //Socket (String host, int port) creates a stream socket and connects it to the specified port number on the specified host.
        Socket s = new Socket("m",10086);
        //Get output stream and write data
        //OutputStream getOutputStream() returns the output stream of this socket.
        OutputStream os  = s.getOutputStream();
        os.write("hello".getBytes());
        //Receive server feedback
        InputStream is = s.getInputStream();
        byte[] bys = new byte[1024];
        int len = is.read(bys);
        String data = new String(bys,0,len);
        System.out.println("client:"+data);
//        int len;
//        while ((len = is.read(bys))!=-1){
//            String data = new  String(bys,0,len);
//            System.out.println("client:" + data);
//        }
        s.close();
        os.close();
        is.close();
    }
    public static void main(String[] args) throws IOException {
        //ServerSocket (int port) creates a server socket bound to a specified port.
        ServerSocket ss = new ServerSocket(10086);
        //Socket accept() listens for the socket to be connected to and accepts it.
        Socket s = ss.accept();
        //Get the input stream, read the data, and display the data on the console
        InputStream is = s.getInputStream();
        byte[] bys = new byte[1024];
        int len = is.read(bys);
        String data = new String(bys,0,len);
        System.out.println("The server:"+data);
//        int len;
//        while ((len = is.read(bys))!=-1){
//            String data = new String(bys,0,len);
//            System.out.println("server:" + data);
//        }
        //Give feedback
        OutputStream os = s.getOutputStream();
        os.write("received".getBytes());

        s.close();
        ss.close();
        os.close();
    }

Data keyboard entry + receiving text file generation exercise

public class Demo {
    public static void main(String[] args) throws IOException {
        Socket s = new Socket("192.168.31.77",10086);
        //Get output stream and write data
        //OutputStream getOutputStream() returns the output stream of this socket.
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        //Encapsulate output stream objects
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
        String line;
        while ((line = br.readLine())!=null){
            if ("886".equals(line)){
                break;
            }
            bw.write(line);
            bw.newLine();
            bw.flush();
            //Receive server feedback
            InputStream is = s.getInputStream();
            byte[] bys = new byte[1024];
            int len = is.read(bys);
            String data = new String(bys,0,len);
            System.out.println("client:"+data);
        }
        s.close();
    }
}
public class ReceiveDemo {
    public static void main(String[] args) throws IOException {
        //ServerSocket (int port) creates a server socket bound to a specified port.
        ServerSocket ss = new ServerSocket(10086);
        //Socket accept() listens for the socket to be connected to and accepts it.
        Socket s = ss.accept();
       //Get the input stream, read the data, and display the data on the console
//        InputStream is = s.getInputStream();
//        InputStreamReader isr = new InputStreamReader(is);
//        BufferedReader br = new BufferedReader(isr);
        BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
        BufferedWriter bw = new BufferedWriter(new FileWriter("untitled1\\copy.txt"));
        String line;
        while((line = br.readLine())!=null){
            System.out.println("The server:"+line);
            bw.write(line);
            bw.newLine();
            bw.flush();
            //Give feedback
            OutputStream os = s.getOutputStream();
            os.write("received".getBytes());
        }
        ss.close();
        bw.close();
    }
}

The data comes from the text file, and the received data is written into the text file

public class Demo {
    public static void main(String[] args) throws IOException {
        Socket s = new Socket("192.168.31.77",10086);
        //Encapsulates the data of a text file
        BufferedReader br = new BufferedReader(new FileReader("untitled1\\osw.txt"));
        //Encapsulate output stream objects
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
        String line;
        while ((line = br.readLine())!=null){
            bw.write(line);
            bw.newLine();
            bw.flush();
            //Receive server feedback
            InputStream is = s.getInputStream();
            byte[] bys = new byte[1024];
            int len = is.read(bys);
            String data = new String(bys,0,len);
            System.out.println("client:"+data);
        }
        s.close();
    }
public class ReceiveDemo {
    public static void main(String[] args) throws IOException {
        //ServerSocket (int port) creates a server socket bound to a specified port.
        ServerSocket ss = new ServerSocket(10086);
        //Socket accept() listens for the socket to be connected to and accepts it.
        Socket s = ss.accept();
       //Get the input stream, read the data, and display the data on the console
//        InputStream is = s.getInputStream();
//        InputStreamReader isr = new InputStreamReader(is);
//        BufferedReader br = new BufferedReader(isr);
        BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
        BufferedWriter bw = new BufferedWriter(new FileWriter("untitled1\\copy.txt"));
        String line;
        while((line = br.readLine())!=null){
            System.out.println("The server:"+line);
            bw.write(line);
            bw.newLine();
            bw.flush();
            //Give feedback
            OutputStream os = s.getOutputStream();
            os.write("received".getBytes());
        }
        ss.close();
        bw.close();
    }
}

The data comes from the text file, and the received data is written into the text file + give feedback

public class Demo {
    public static void main(String[] args) throws IOException {
        Socket s = new Socket("192.168.31.77",10086);
        //Encapsulates the data of a text file
        BufferedReader br = new BufferedReader(new FileReader("untitled1\\osw.txt"));
        //Encapsulate output stream objects
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
        String line;
        while ((line = br.readLine())!=null){
            bw.write(line);
            bw.newLine();
            bw.flush();
        }
        //Custom end ID
//        bw.write("886");
//        bw.newLine();
//        bw.flush();
        //void shutdownOutput() disables the output stream for this socket. (end of output)
        s.shutdownOutput();

        //Receive server feedback
        BufferedReader brus = new BufferedReader(new InputStreamReader(s.getInputStream()));
        String data = brus.readLine();
        System.out.println("Feedback from the server:"+data);
        s.close();
    }
}
public class ReceiveDemo {
    public static void main(String[] args) throws IOException {
        //ServerSocket (int port) creates a server socket bound to a specified port.
        ServerSocket ss = new ServerSocket(10086);
        //Socket accept() listens for the socket to be connected to and accepts it.
        Socket s = ss.accept();
       //Get the input stream, read the data, and display the data on the console
        BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
        BufferedWriter bw = new BufferedWriter(new FileWriter("untitled1\\copy.txt"));
        String line;
        while((line = br.readLine())!=null){
            if ("886".equals(line)){
                break;
            }
            System.out.println("The server:"+line);
            bw.write(line);
            bw.newLine();
            bw.flush();
        }
        //Give feedback
        BufferedWriter bwServer = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
        bwServer.write("Upload successful");
        bwServer.newLine();
        bwServer.flush();
        ss.close();
        bw.close();
    }
}

There is a problem that the program has been waiting (because the method of reading data is blocking)

Solution: customize the end tag; Use void shutdownOutput() to disable the output stream for this socket. (end of output) method

Multi thread file upload exercise (the client is the same as the previous exercise)

public class ServerThread implements Runnable {
    private Socket s;
    public ServerThread(Socket s) {
        this.s=s;
    }
    @Override
    public void run() {
        try {
            //BufferedWriter bw = new BufferedWriter(new FileWriter("untitled1\\copy.txt"));
            //Resolve name conflicts
            int count = 0;
            File file = new File("untitled1\\copy["+count+"]txt");
            while (file.exists()){
                count++;
                file = new File("untitled1\\copy["+count+"]txt");
            }
            BufferedWriter bw = new BufferedWriter(new FileWriter(file));
            BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));

            String line;
            while ((line=br.readLine())!=null){
                bw.write(line);
                bw.newLine();
                bw.flush();
                System.out.println("The server:"+line);
            }
            //Give feedback
            BufferedWriter bwServer = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
            bwServer.write("Upload successful");
            bwServer.newLine();
            bwServer.flush();

            s.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
public class ReceiveDemo {
    public static void main(String[] args) throws IOException {
        //ServerSocket (int port) creates a server socket bound to a specified port.
        ServerSocket ss = new ServerSocket(10086);
        while (true){
            //Socket accept() listens for the socket to be connected to and accepts it.
            Socket s = ss.accept();
            //Start a thread for each client
            new Thread(new  ServerThread(s)).start();
        }
    }
}

Lambda expression

Experience lambda expressions

public class LambdaDemo {
    public static void main(String[] args) {
        //Anonymous inner class override multithreading
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                System.out.println("multithreading");
//            }
//        }).start();
        // Improvement of Lambda expression
        new Thread(()->{
            System.out.println("Multithreading");
        }).start();
    }
}

The three elements that make up a Lambda expression: formal parameters, arrows, and code blocks

Lambda expression format

Format: (formal parameter) - > {code block}

Formal parameters: if there are multiple parameters, the parameters are separated by commas; if there are no parameters, leave them blank

->: it is composed of the line drawn in the text and the greater than symbol. It is written in a fixed way and represents the pointing action

Code block: it is the specific thing we need to do, that is, the content of the method body we wrote before

Lambda expression exercise

Premise of Lambda expression

There is an interface

There is only one abstract method in the interface

Omission mode of Lanbda expression

Omission rule:

Parameter types can be omitted, but when there are multiple parameters, only one cannot be omitted

If there is only one parameter, the parentheses can be omitted

If there is only one statement in the code block, you can omit braces, semicolons, or even return

matters needing attention:

To use Lambda, there must be an interface, and there must be only one abstract method in the interface

The interface corresponding to Lambda can only be deduced if there is a context

Get the value of the corresponding variable of the interface: runnable -. Lambda = > out. Println ("lambda expression");

According to the parameters of the calling method, you can know the interface corresponding to lambda: new thread (() - > system out. println("Lambda")). start();

        Runnable r =()-> System.out.println("Lambda expression");
        new Thread(r).start();
        new Thread(()->System.out.println("Lambda")).start();

The difference between Lambda expressions and anonymous inner classes

Different types required

Anonymous inner class: it can be an interface, an abstract class or a concrete class

Lambda expression: can only be an interface

Different use restrictions

If there is only one abstract method in the interface, you can use Lambda expressions or anonymous inner classes

If there is more than one abstract method in the interface, only anonymous inner classes can be used, not Lambda expressions

Different implementation principles

Anonymous inner class: after compilation, a separate class is generated Class bytecode file

Lambda expression: after compilation, there is no single expression class bytecode file, the corresponding bytecode will be automatically generated during operation

Interface composition update

Interface composition update overview

Composition of interface

Constant: public static final

Abstract method: public abstract

Default method (Java8)

Static method (Java 8)

Private method (Java 9)

Default method in interface

Definition format of default method in interface:

Format: public default return value type method name (parameter type) {}

Example: public default void show3() {}

Precautions for interfaces and default methods:

The default method is not an abstract method, so it is not forced to be overridden. But it can be rewritten. When rewriting, remove the default keyword

public can be omitted, but default cannot be omitted

Static methods in interfaces

Definition format of static method in interface:

Format: public static return value type method name (parameter list) {}

Example: public static void show() {}

Precautions for static methods in the interface:

Static methods can only be called through the interface name, not through the implementation class name or object name

public can be omitted, but static cannot be omitted

Private method in interface

Definition format of private method in interface:

Format 1: private return value class name method name (parameter list) {}

Example 1: private void show() {}

Format 2: private static return value type method name (parameter list) {}

Example 2: private static void method() {} (static methods can only call static methods)

Precautions for private methods in the interface:

The default method can call static and non static methods of private methods

Static methods can only call private static methods

Method reference

    public static void main(String[] args) {
        useInter(s->{
            System.out.println(s);
        });
        //Method reference:
        useInter(System.out::println);
        //What can be deduced is what can be omitted
    }

Method reference

: this symbol is a reference operator, and its expression is called a method reference

Push to and omit

If Lambda is used, according to the principle of "can be deduced and can be omitted", there is no need to specify the parameter type or overload form, and they will be deduced automatically

If method reference is used, it can also be deduced according to the context

Method references are Lambda's twin brothers

Reference class method (static method of reference class)

Format: Class Name:: static method

Example: Integer::parseInt

Method of Interger class: convert public static int parseInt(String) to int type data

   public static void main(String[] args) {
        useConverter(s-> Integer.parseInt(s)
        );
        useConverter(Integer::parseInt);
    }

    private static void useConverter(Converter c) {
        int cn = c.convert("9999");
        System.out.println(cn);
    }

When a Lambda expression is replaced by a class method, all its formal parameters are passed to the static method as parameters

Instance method of reference object

Format: object:: member method

Example: "HelloWorld"::toUpperCase

The method in the String class: public String toUpperCase() converts all characters of this String to uppercase

public class PrintString {
    public void printUpper(String s){
        System.out.println(s.toUpperCase());
    }
}


public interface Printer {
    void PrintUpperCase(String s);
}

public class PrinterDEmo {
    public static void main(String[] args) {
//        usePrinter((String s)->{
//            System.out.println(s.toUpperCase());
//        });
        //Reference object instance method
        PrintString p = new PrintString();
        usePrinter(p::printUpper);
    }

    private static void usePrinter(Printer p) {
        p.PrintUpperCase("HelloWorld");
    }
}

When a Lambda expression is replaced by an instance method of an object, all its formal parameters are passed to the method as parameters

Instance method of reference class

Format: Class Name:: member method

Example: String::substring

Method in String class: public String substring(int beginIndes,int endIndex)

Intercept the string from beginIndex to endIndex. Returns a substring whose length is endIndex beginIndex

public interface MyString {
     String mySubString(String s ,int x ,int y);
}

public class MyStringDemo {
    public static void main(String[] args) {
//        useMyString((s,x,y)->{
//           return s.substring(x,y);
//        });
        useMyString((s,x,y)->s.substring(x,y));

        //Instance method of reference class
        useMyString(String::substring);
    }
    private static void useMyString(MyString my){
        String s = my.mySubString("HelloWorld", 2, 5);
        System.out.println(s);
    }
}

When a Lambda expression is replaced by an instance method of a class, the first parameter is used as the caller, and all subsequent parameters are passed to the method as parameters

Reference constructor (reference constructor)

Format: Class Name:: new

Example: Student::new

public interface StudentBuilder {
    Student build(String name,int age);
}

public class StudentDemo {
    public static void main(String[] args) {
//        useStudentBuilder((name,age)->{
//           return new Student(name,age);
//        });
        useStudentBuilder(((name, age) -> new Student(name,age)));
        //Reference constructor
        useStudentBuilder(Student::new);
    }

    private static void useStudentBuilder(StudentBuilder s) {
        Student sm = s.build("xiaohuang", 30);
        System.out.println(sm.getName()+","+sm.getAge());
    }

}

When a Lambda expression is replaced by a constructor, all its formal parameters are passed to the constructor as parameters

Functional interface (Lambda expression is applicable): an interface with only one abstract method

@FunctionalInterface
public interface MyInterface {
    void show();
}

public class MyInterfaceDemo {
    public static void main(String[] args) {
        MyInterface my = ()-> System.out.println("Functional interface");
        my.show();
    }
}

@Functional interface is placed above the interface definition. If the interface is a functional interface, the compilation passes. If not, the compilation fails

Note: when defining a functional interface, @ FunctionalInterface is optional. Do not write this annotation. As long as the definition conditions of the functional interface are met, it is recommended to add this annotation when the functional interface is the same.

Functional interface as parameter of method

If the parameter of the method is a functional interface, we can use Lambda expression as the parameter

        startThread(()->System. out. println(Thrasd.currentThread(). Getname() + "thread start");

The functional interface is used as the return value of the method

public class MyInterfaceDemo {
    public static void main(String[] args) {
        ArrayList<String> ar = new ArrayList<String>();

        ar.add("bb");
        ar.add("ddddd");
        ar.add("aaa");
        ar.add("cccc");
        System.out.println(ar);
        Collections.sort(ar,getComparator());
        System.out.println(ar);

    }
    private static Comparator<String> getComparator(){
        //Anonymous Inner Class 
//       Comparator<String> cp = new Comparator<String>() {
//           @Override
//           public int compare(String o1, String o2) {
//               return o1.length()-o2.length();
//           }
//       };
//       return cp;


//        return new Comparator<String>() {
//           @Override
//           public int compare(String o1, String o2) {
//               return o1.length()-o2.length();
//           }
//       };

        return (s1,s2)-> s1.length()-s2.length();
    }
}

If the return value of a method is a functional interface, we can use a Lambda expression as the return result

Common functional interfaces

Supplier interface

Supplier < T >: contains a parameterless method

        T get(); Obtain results

This method does not require parameters. It will return a data according to some implementation logic (implemented by Lambda expression)

The supplier < T > interface is also called a production interface. If we specify the generic type of the interface, the get method in the interface will produce what type of data for us to use

    public static void main(String[] args) {
        String s = getString(() -> "xiaobai");

        System.out.println(s);
    }
    private static String getString(Supplier<String> sup){
        return sup.get();
    }

Consumer interface

Consumer < T >: contains two methods

Void accept (T): perform this operation on the given parameter

Default Consumer < T > and then (Consumer after): return a combined Consumer, perform this operation once, and then perform the after operation

The consumer < T > interface is also called a consumption interface. The data type of the data it consumes is specified by the generic type

    public static void main(String[] args) {
        operatorString("xiaohuang",(String s )->{
            System.out.println(s);
        });
        operatorString("xiaolv",s-> System.out.println(s));
        operatorString("xiaolan",System.out::println);
        operatorString("xiaohei",s->
            System.out.println(new StringBuilder(s).reverse().toString()));
        operatorString("xiaofen",s-> System.out.println(s),s -> System.out.println(new StringBuilder(s).reverse().toString()));
    }
    //Define a method to consume the same string data twice in different ways
    private static void operatorString(String name, Consumer<String> con1,Consumer<String> con2){
//        con1.accept(name);
//        con2.accept(name);
        con1.andThen(con2).accept(name);
    }


    private static void operatorString(String name, Consumer<String> con){
        con.accept(name);
    }

practice

    public static void main(String[] args) {
        String[] sa = {"xiaohong,12","xiaocheng,15","xiaohuang,18"};
        printInfo(sa,(String s)->{
            String name = s.split(",")[0];
            System.out.print("full name"+name);
        },(String s)->{
            int age = Integer.parseInt(s.split(",")[1]);
            System.out.println(",Age"+age);
        });
    }
    //Define a method to consume the same string data twice in different ways
    private static void printInfo(String[] sa, Consumer<String> con1,Consumer<String> con2){
        for (String s : sa){
            con1.andThen(con2).accept(s);
        }
    }

Predict interface

Predict < T >: four common methods

Boolean test (T): judge the given parameter (the judgment logic is implemented by Lambda expression) and return a Boolean value

default predicate < T > negate(): returns a logical negation, corresponding to a logical negation

default predicate < T > and (predicate other): returns a combined judgment, corresponding to short circuit and

default predict < T > or (predict other): return a combination judgment, corresponding to short circuit or

The predict < T > interface is usually used to judge whether the parameters meet the specified conditions

    public static void main(String[] args) {
        boolean b = chechString("hellojava", s -> s.length() > 8);
        System.out.println(b);
        boolean b1 = checkString("helloworld", s -> s.length() > 8, s -> s.length() < 16);
        System.out.println(b1);
    }
    private static boolean chechString(String s , Predicate<String> p){
        return p.negate().test(s);
    }
    private static boolean checkString(String s, Predicate<String> p1, Predicate<String> p2){
//        return p1.test(s)&&p2.test(s);
        return p1.and(p2).test(s);
    }

Screening exercise

    public static void main(String[] args) {
        String[] ss = {"xiaohong,12","xiaocheng,15","xiaohuang,18","xiaolv,17"};
        checkString(ss, s -> s.split(",")[0].length() > 8, s -> Integer.parseInt(s.split(",")[1]) > 16);

    }
    private static void checkString(String[] ss, Predicate<String> p1, Predicate<String> p2){
//        return p1.test(s)&&p2.test(s);
        boolean test = false;
        for (String s : ss) {
             test = p1.and(p2).test(s);
            if (test){
                System.out.println(s);
            }
        }
    }

Function interface

Function < T, R >: two commonly used methods

R apply (T): apply this function to the given parameter

Default < T > function and then (function after): returns a composite function. First apply the function to the input, and then apply the after function to the result

The function < T, R > interface is usually used to process parameters, convert (the processing logic is implemented by Lambda expressions), and then return a new value

    public static void main(String[] args) {
        convert("555",s->Integer.parseInt(s),s->String.valueOf(s+111));
    }
    private static void convert(String s, Function<String,Integer> fun1,Function<Integer,String> fun2){
//        String ss = fun2.apply(fun1.apply(s));
       String ss = fun1.andThen(fun2).apply(s);
        System.out.println(ss);
    }

Topics: Network Protocol udp TCP/IP