Functional interface Consumer, BiConsumer, Supplier, Predicate, Function, BiFunction

Functional interface Consumer, BiConsumer, Supplier, Predicate, Function, BiFunction

1. Consumer

The Java Consumer interface comes from the java.util.function package introduced in Java 8.
Consumer is a functional interface used as a task target for lambda expressions or method references (passing a parameter to execute the specified method).

The functional interface of Consumer is an operation that accepts a single parameter and returns no result. When necessary, “results” can exist in collections

The functional method of Consumer is accept(T t).

Consumer has the following methods.

  1. accept : This is a functional method of the Consumer functional interface. The accept method does this for the given arguments.
  2. andThen : This method returns a combined Consumer that first performs the original Consumer operation, then performs the given andThen operations in left-to-right order

Example

import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;

public class Test0807 {<!-- -->
    public static void main(String[] args) {<!-- -->
        
        Consumer<Integer> print = i -> System.out.print(i);
        //1
        print. accept(1);
        System.out.println("----------------->");


        List<Integer> list = Arrays. asList(1, 2, 3, 4);
        //Each element of the collection is multiplied by 5
        Consumer<List<Integer>> change=i->{<!-- -->
            for (int j = 0; j < i. size(); j ++ ) {<!-- -->
                i.set(j,i.get(j)*5);
            }
        };
        // print each element
        Consumer<List<Integer>> print1=i->{<!-- -->
            for (int j = 0; j < i. size(); j ++ ) {<!-- -->
                System.out.print(i.get(j) + " ");
            }
        };
        // Each is multiplied by 5 before printing
        //5 10 15 20
        change.andThen(print1).accept(list);
    }
}

Instance usage

public class Test0807 {<!-- -->

    public static void main(String[] args) {<!-- -->
        List<Integer> list = Stream.of(1, 2, 3, 4).collect(Collectors.toList());
        list.forEach(i->System.out.println(i));
    }

2. BiConsumer

The Java BiConsumer interface comes from the java.util.function package introduced in Java 8.
BiConsumer is a functional interface used as a task target of a lambda expression or method reference (passing two parameters to execute the specified method).

The functional interface of BiConsumer is an operation that accepts two parameters and returns no results.

The functional method of BiConsumer is accept(T t, U u).

BiConsumer has the following methods.

  1. accept : This is a functional method of the Consumer functional interface. The accept method does this for the given arguments.
  2. andThen : This method returns a composed BiConsumer that first performs the original BiConsumer operation, then performs the given andThen operations in left-to-right order

Example

import com.google.common.collect.Maps;

import java.util.Map;
import java.util.function.BiConsumer;

public class Test0807 {<!-- -->

    public static void main(String[] args) {<!-- -->

        BiConsumer<String,Integer> print = (K,V) -> System.out.println(K + ":" + V);
        print. accept("1",2);
        System.out.println("----------------->");

        Map<String,Integer> map = Maps. newLinkedHashMap();
        for (int i = 0; i < 10; i ++ ) {<!-- -->
            map. put(i + "", i);
        }

        //Print key splicing a
        BiConsumer<String,Integer> print1=(K,V)->{<!-- -->
            System.out.println("keyChange--->" + K.concat("a") + ":" + V);
        };

        //print value multiplied by 2
        BiConsumer<String,Integer> print2=(K,V)->{<!-- -->
            System.out.println("valueChange--->" + K + ":" + V*2);
        };

        //Print the key and splicing a and then print the value and multiply it by 2
        for (Map.Entry<String, Integer> entry : map.entrySet()) {<!-- -->
            print1.andThen(print2).accept(entry.getKey(), entry.getValue());
        }
    }
}

Actual use

import java.util.HashMap;
import java.util.Map;

public class Test0807 {<!-- -->

    public static void main(String[] args) {<!-- -->
        Map<Integer, String> map=new HashMap<>();
        map. put(1,"a");
        map. put(2,"b");
        map. put(3,"c");
        map. put(4,"d");
        map.forEach((k,v)->{<!-- -->
            System.out.println(k + ":" + v);
        });
    }
}

3. Supplier

The Java Supplier interface comes from the java.util.function package introduced in Java 8.
Supplier is a functional interface that represents a provider of results.

The functional interface of a Supplier is an operation that takes no arguments and gets a result.

The function method of Supplier is get()

Example

import com.google.common.collect.Lists;

import java.util.List;
import java.util.Random;
import java.util.function.Supplier;

public class Test0807 {<!-- -->

    public static void main(String[] args) {<!-- -->
        Supplier<Integer> supplier=()->new Random().nextInt(10) + 1;
        List<Integer> list = Lists. newArrayList();
        for (int i = 0; i < 10; i ++ ) {<!-- -->
            list.add(supplier.get());
        }
        list.forEach(i->System.out.println(i));
    }
}

Actual use

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

public class Test0807 {<!-- -->

    public static void main(String[] args) {<!-- -->
        Map<Integer, String> map=new HashMap<>();
        map. put(1,"a");
        map. put(2,"b");
        map. put(3,"c");
        map. put(4,"d");
        ArrayList<Map.Entry<Integer, String>> collect = map.entrySet().stream().collect(Collectors.toCollection(() -> new ArrayList<>()));
        //Equivalent to
        //ArrayList<Map.Entry<Integer, String>> collect = map.entrySet().stream().collect(Collectors.toCollection(ArrayList::new));
        System.out.println("collect = " + collect);
    }
}

4. Predicate

The Java Predicate interface comes from the java.util.function package introduced in Java 8.

Predicate is a function that returns a boolean value.

Method name Function
test(T t) Judge whether the object t satisfies the condition, return true if satisfied, return false if not satisfied
and(Predicate other) Judge whether the object t satisfies the current condition and the other condition at the same time, return true if it is satisfied, and return false if it is not satisfied, which is equivalent to short circuit and & amp; & amp;
negate() Invert the result of test(T t)
or(Predicate other) Judging object t Whether the current condition is satisfied or the other condition is satisfied, true is returned if it is satisfied, and false is returned if it is not satisfied, which is equivalent to a short circuit or ||
isEqual(Object targetRef) Determine whether the current object is equal to the targetRef attribute value of the object, which is equivalent to Objects.equals(Object a, Object b)

Example:

import lombok.Data;
import lombok.experimental.Accessors;
import org.apache.commons.lang3.StringUtils;

import java.util.function.Predicate;

public class Test0807 {<!-- -->

    public static void main(String[] args) {<!-- -->
        Stu stu1 = new Stu().setAge(20).setName("Zhang San").setSex("Male");

        //whether the age is greater than 20
        Predicate<Stu> condition1=i->i.getAge()>20;
        //whether the gender is female
        Predicate<Stu> condition2=i-> StringUtils.equals("Female",i.getSex());

        //Judge whether the age of stu1 is greater than 20
        boolean test1 = condition1. test(stu1);
        System.out.println("test1 = " + test1);//false

        //negate negates the result
        boolean test11 = condition1.negate().test(stu1);
        System.out.println("test11 = " + test11);//false

        //Judge whether stu1 is female
        boolean test2 = condition2. test(stu1);
        System.out.println("test2 = " + test2);//false

        //Judge whether stu1 is older than 20 and gender is female at the same time
        stu1.setAge(25);
        boolean test3 = condition1.and(condition2).test(stu1);
        System.out.println("test3 = " + test3);//false

        //Judge whether stu1 is older than 20 or gender is female
        boolean test4 = condition1.or(condition2).test(stu1);
        System.out.println("test4 = " + test4);//true

        //Judge whether stu and stu1 are equals
        Stu stu = new Stu().setSex("Male").setAge(25).setName("Zhang San");
        boolean test5 = Predicate.isEqual(stu).test(stu1);
        System.out.println("test5 = " + test5);//true
    }
}

@Data
@Accessors(chain = true)
class Stu{<!-- -->

    private String name;

    private Integer age;

    private String sex;
}

Actual use

import com.google.common.collect.Lists;

import java.util.List;

public class Test0807 {<!-- -->

    public static void main(String[] args) {<!-- -->
        List<Integer> list = Lists. newArrayList();
        for (int i = 0; i < 10; i ++ ) {<!-- -->
            list. add(i);
        }
        // output even number
        list.stream().filter(i -> i % 2 == 0).forEach(i->System.out.println(i));

    }
}

5. Function

The Java Function interface comes from the java.util.function package introduced in Java 8.

Function is a functional interface used as a task target of a lambda expression or method reference (passing a parameter to execute the specified method).

The functional interface of Function is an operation that takes a single argument and returns a single result.

The function method of Function is R apply(T t);

Function has the following methods

Method name Function
R apply(T t); Return R after performing function operations on the incoming parameter t
compose(Function before) First perform the before function operation on the incoming parameters, and then perform the current function operation on the basis of the before function operation
andThen(Function after) First perform the current function operation on the incoming parameters, and then perform the after function operation on the basis of the current function operation
identity () Return whatever you enter

Example:

public class Test0807 {<!-- -->

    public static void main(String[] args) {<!-- -->

        Function<Integer,Integer> multi=i->i*10;
        Integer result = multi.apply(10);
        System.out.println("result = " + result);

        Function<Integer,Integer> add=i -> i + 10;
        //First add 10 and then multiply by 10
        result = multi.compose(add).apply(10);//(10 + 10)*10
        System.out.println("result = " + result);
        //First multiply by 10 and then add 10
        result = multi.andThen(add).apply(10);//10*20 + 10
        System.out.println("result = " + result);
    }
}

Actual use

import com.google.common.collect.Lists;

import java.util.List;

public class Test0807 {<!-- -->

    public static void main(String[] args) {<!-- -->
        List<Integer> list = Lists. newArrayList();
        for (int i = 0; i < 10; i ++ ) {<!-- -->
            list. add(i);
        }
        list.stream().map(i -> i * 2).forEach(i->System.out.println(i));
    }
}

6. BiFunction

The Java BiFunction interface comes from the java.util.function package introduced in Java 8.

BiFunction is a functional interface used as a task target of a lambda expression or method reference (passing two parameters to execute the specified method).

The functional interface of BiFunction is an operation that accepts two parameters and returns a single result.

The function method of BiFunction is R apply(T t, U u);

BiFunction has the following methods

  1. apply: This is the function method of the BiFunction functional interface. The apply method does this for the given arguments.
  2. andThen : This method returns a combined BiFunction that first performs the original BiFunctionr operation, then performs the given andThen operations in left-to-right order

Example:

import java.util.function.BiFunction;

public class Test0807 {<!-- -->

    public static void main(String[] args) {<!-- -->
        //value*10
        BiFunction<String,Integer,Integer> biFunction1=(K,V)->{<!-- -->
            V=V*10;
            return V;
        };
        Integer a = biFunction1.apply("a", 10);
        System.out.println("a = " + a);//10

        //value + 10
        Integer a1 = biFunction1.andThen(i -> i + 10).apply("a", 10);//10*10 + 10
        System.out.println("a1 = " + a1);


        //key uppercase
        BiFunction<String,Integer,String> biFunction2=(K,V)->{<!-- -->
            K=K.toUpperCase();
            return K;
        };
        String a2 = biFunction2. apply("a", 10);
        System.out.println("a2 = " + a2);//A

        // stitching itself
        String a3 = biFunction2.andThen(i -> i.concat(i)).apply("a", 10);
        System.out.println("a3 = " + a3);//AA


    }
}

Actual use

import java.util.HashMap;
import java.util.Map;

public class Test0807 {<!-- -->

    public static void main(String[] args) {<!-- -->
        Map<Integer, String> map=new HashMap<>();
        map. put(1,"a");
        map. put(2,"b");
        map. put(3,"c");
        map. put(4,"d");
        //value uppercase
        map.keySet().forEach(i->{<!-- -->
            map.computeIfPresent(i, (K, V) -> V.toUpperCase());
        });
        map.forEach((K,V)-> System.out.println(K + ":" + V));
    }
}