Java common function interface - Consumer Interface

 

JDK provides a number of interface functions common to enrich Lambda typical usage scenario, they are mainly  supplied java.util.function package. The following is a simple example of the use of Consumer interfaces.

Consumer Interface Overview

@FunctionalInterface
public interface Consumer<T> {

    /**
     * Consumption of given parameters to perform the operation.
     *
     * @Param T input parameter
      * / 
    void Accept (T T);

    default Consumer<T> andThen(Consumer<? super T> after) {
        Objects.requireNonNull(after);
        return (T t) -> { accept(t); after.accept(t); };
    }
}

 java.util.function.Consumer <T> is just an interface with the Supplier interfaces contrary, it is not a production data, but rather a data consumer, the data type determined by the generic.

 

Abstract methods: accept

Consumer interfaces include an abstract method void accept (T t), are intended consumption data is designated as a generic. The basic use such as:

import java.util.function.Consumer;

public class Demo01Consumer {
    public static void main(String[] args) {
        consumerString(s -> System.out.println(s));
    }

    private static void consumerString(Consumer<String> function) {
        function.accept("Hello");
    }
}

Run the program, the console output:

Hello

Of course, a better method is to use written references.

 

The default method: andThen

If a method parameter and return value are all Consumer types, then you can achieve the effect: consumption data, the first thing to do an operation, and then make an operation, to achieve combination. And this way is default method Consumer interface andThen.

default Consumer<T> andThen(Consumer<? super T> after) {
    Objects.requireNonNull(after);
    return (T t) -> { accept(t); after.accept(t); };
}
Note: java.util.Objects of requireNonNull static method will take the initiative to throw in the parameter is null
 NullPointerException exception. This eliminates the need for rewriting the if statement and throws null pointer exception trouble.

 

To achieve the combination, two or more Lambda expressions can be, and andThen semantics is the "step by step" operation. For example in the case of a combination of two steps:

import java.util.function.Consumer;

public class Demo02Consumer {
    public static void main(String[] args) {
        consumerString(
                // the toUpperCase () method to convert a string to upper case 
                S -> System.out.println (s.toUpperCase ()),
                 // the toLowerCase () method to convert strings to lower 
                S -> System.out.println (s.toLowerCase ())
        );
    }

    private static void consumerString(Consumer<String> one, Consumer<String> two) {
        one.andThen(two).accept("Hello");
    }
}

The results will first print run entirely uppercase HELLO, then print entirely lowercase hello. Of course, additional steps may be implemented by a combination of chain wording.

HELLO
hello

 

Exercise: formatted print information

topic

The following array of strings among the pieces of information there, follow the format " Name:. XX: XX sex." The format will print out the information. The printing operation requires as a first name Lambda Consumer interface instance, the print operation as the second sex Lambda Consumer interface instance, the two Consumer Interface order "spliced" together.

String [] array = { "Nobita, M", "Shizuka, female", "Pan Hu, M"};

 

answer

import java.util.function.Consumer;

public class DemoPrintInfo {
    public static void main(String[] args) {
        String [] Array = { "Nobita, M", "Shizuka, female", "Pan Hu, M" };

        printInfo(
                s -> System.out.print("姓名:" + s.split(",")[0] + ","),
                s -> System.out.println("性别:" + s.split(",")[1] + "。"),
                array
        );
    }

    private static void printInfo(Consumer<String> one, Consumer<String> two, String[] array) {
        for (String info : array) {
            one.andThen(two).accept(info);
        }
    }
}

Run the program, the console output:

Name: Nobita, Gender: Male.
Name: Shizuka, Gender: Female.
Name: Pan Hu, Gender: Male.

 

          

Guess you like

Origin www.cnblogs.com/liyihua/p/12286086.html