Consumer, Supplier, Predicate and Function of Java 8

Keywords: Java Back-end java8

         Today, I looked at the new features of Java 8 and saw that some of the sample code called these function interfaces. I was confused~

So the blogger checked the information to see what these function interfaces are useful for, so that it is easy to understand later. There is no more nonsense. Let's start!!

1.Consumer interface

        As the name suggests, this is a consumer interface. It passes in parameters and then outputs values without returning values; In the popular point, you pass a parameter in, you can adjust the parameter you want, and then output it. End!

The following describes the usage and common accept(), andThen() methods, as well as other Consumer interfaces:

  • accept(T t)          Provide T-type input parameters and do not return execution results  
StringBuilder sb = new StringBuilder("Hello ");
//Here is the rule I defined. The incoming string splices the "Jack" string
Consumer<StringBuilder> consumer = (str) -> str.append("Jack!");
consumer.accept(sb);
//Output after splicing
System.out.println(sb.toString());	// Hello Jack!
  • andThen(Consumer<? super T> after)   Splicing the rules of the previous consumer  
Consumer<StringBuilder> consumer1 = (str) -> str.append(" Bob!");
consumer.andThen(consumer1).accept(sb);
System.out.println(sb.toString());	// Hello Jack! Bob!
  •   BiConsumer<T,U>   Two user-defined parameters are provided and no execution result is returned, which means that you can enter two values for processing
StringBuilder sb = new StringBuilder();
BiConsumer<String, String> biConsumer = (a, b) -> {
	sb.append(a);
	sb.append(b);
};
biConsumer.accept("Hello ", "Jack!");
System.out.println(sb.toString());	// Hello Jack!
  • At the same time, the Consumer can also be passed into other methods, as follows:
// Using lambda expressions, all the forEach method needs is a Consumer interface
// The Stream.of method means to put the values of parentheses into Stream in order
Stream<String> stream = Stream.of("aaa", "bbb", "ddd", "ccc", "fff");
Consumer<String> consumer1 = (s) -> System.out.println(s);
//The lambda expression returns a Consumer interface
stream.forEach(consumer1);
//More direct way
//stream.forEach((s) -> System.out.println(s));

  Summary:

① In addition to the above, there are interfaces such as IntConsumer and DoubleConsumer, which are used in the same way as above

 

  2.Supplier interface  

         The Supplier interface is a supply interface. In fact, it is a container that can be used to store data and then be used by other methods. Do you understand it very well? If you still don't understand it, take a look at the following examples and you will understand it completely!

    /**
     * Supplier For interface testing, the supplier is equivalent to a container or variable that can store values
     */
    @Test
    public void test_Supplier() {
        //1, The Supplier interface is used to implement the method. There is only one get method, no parameters, and a value is returned
        Supplier<Integer> supplier = new Supplier<Integer>() {
            @Override
            public Integer get() {
                //Returns a random value
                return new Random().nextInt();
            }
        };

        System.out.println(supplier.get());

        System.out.println("********************");

        //2, Using lambda expressions,
        supplier = () -> new Random().nextInt();
        System.out.println(supplier.get());
        System.out.println("********************");

        //3, Use method reference
        Supplier<Double> supplier2 = Math::random;
        System.out.println(supplier2.get());
    }

  Use the interface method that requires the Supplier, such as the method that requires the Supplier interface for the optional object

    @Test
    public void test_Supplier2() {
        Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5);
        //Returns an optional object
        Optional<Integer> first = stream.filter(i -> i > 4)
                .findFirst();

        //The optional object has a method that requires a Supplier interface
        //orElse, if there is a number in the first, it will return the number. If it does not exist, it will return the passed in number
        System.out.println(first.orElse(1));//Output result 5
        System.out.println(first.orElse(7));//Output result 5

        System.out.println("********************");

        Supplier<Integer> supplier = new Supplier<Integer>() {
            @Override
            public Integer get() {
                //Returns a random value
                return new Random().nextInt();
            }
        };

        //orElseGet: returns the number if it exists in the first. If it does not exist, returns the value returned by the supplier
        System.out.println(first.orElseGet(supplier));//Output result 5
    }

Summary:
① . in addition to the Supplier interfaces used above, you can also use the following Supplier interfaces.
IntSupplier, DoubleSupplier, LongSupplier and Boolean supplier are used in the same way as above.

② The. Supplier interface can be understood as a container for storing data.

③ The. Supplier interface has a   get   Method to return a value.

 

3. Predict interface

         The Predicate interface is a Predicate interface. In fact, it is a judgment interface similar to bool type

  • Test (T) performs an operation on a given input parameter and returns a boolean result (Boolean function)
Predicate<Integer> predicate = number -> number != 0;
System.out.println(predicate.test(10));    //true
  • and(Predicate<? super T> other)   Splice a predicate condition
//Take on the above code
predicate = predicate.and(number -> number >= 10);
System.out.println(predicate.test(10));    //true
  • or(Predicate<? super T> other)   Just or
// Accept the above code
predicate = predicate.or(number -> number != 10);
System.out.println(predicate.test(10));    //true
  •   negate()   This is negation
// Accept the above code
predicate = predicate.negate();
System.out.println(predicate.test(10));    //false

 

Summary:
① . you can also use the doublepredicte interface in the same way as above.

② The. Predict interface can be understood as an interface used to judge conditions

 

 

4.Function interface

         function is used to convert, receive a parameter and return a result;

         Function < T, R > where T represents the input parameter and R represents the return parameter

        Let's take a look at the examples and introduce the common methods

  • apply(T t)
    // For example, like the defined generics, the input parameters are of type String and the returned parameters are of type Integer
    Function<String,Integer> test=i->Integer.parseInt(i)+1;
    test.apply("5");// 6

  • andThen(Function<? super R, ? extends V> after)   Execute name first, then square
Function<Integer, Integer> name = e -> e * 2;
Function<Integer, Integer> square = e -> e * e;
int value = name.andThen(square).apply(3);// 36
  • compose(Function<? super V, ? extends T> before)   Execute square first, and then execute name
//Accept the above code
int value2 = name.compose(square).apply(3);// 18

Summary:

① . in addition to the Function interfaces used above, you can also use the following Function interfaces.
IntFunction, DoubleFunction, LongFunction, ToIntFunction, ToDoubleFunction, DoubleToIntFunction, etc. the use method is the same as above.

② . Function interface is a functional interface, which is used to convert data.
③ . Function interface implementation   apply   Method to do the conversion.  

Posted by cocpg on Thu, 21 Oct 2021 08:17:31 -0700