Commonly used numerical interfaces in Java

When learning lambda expressions, we know that to use lambda expressions, we have to create a functional interface. Then every time we use lambda expressions, we have to manually create an interface. Isn't it very troublesome? At that time, java gave us four built-in core functional interfaces.

1. Consumer: consumer interface, void accept(T t)

The Consumer interface represents an operation that accepts an input parameter and returns no return. Examples are as follows:

public static void main(String[] args) {
    
    
        Consumer<String> consumer = (name)-> System.out.println("我叫"+name);
        consumer.accept("张三");
    }

2. Supplier: supply interface, T get()

Supply parameters represent no parameters and return a result

SimpleDateFormat dateFormat = new SimpleDateFormat("yy-MM-dd hh:mm:ss");
        Supplier supplier = Date::new;
        System.out.println("当前时间是:"+ dateFormat.format(supplier.get()));

operation result:
insert image description here

3. Function<T, R> : functional interface, R apply(T t)

Takes one input parameter and returns a result

Function<Double,String> function = (num) -> "消费"+num+"元";
        System.out.println(function.apply(32.1));;

4. Predicate: assertion interface, boolean test(T t)

Pass in a parameter, according to this parameter, return a boolean type.

 public static void main(String[] args) {
    
    
        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
        System.out.println("输出所有偶数");
        eval(list,(n)->n%2 == 0);

    }

    public static void eval(List<Integer> list, Predicate<Integer> predicate) {
    
    
        for(Integer n: list) {
    
    

            if(predicate.test(n)) {
    
    
                System.out.println(n + " ");
            }
        }
    }

5. Other interfaces

In addition to the above functional interfaces, java also has some other functional interfaces built in. Generally, you only need to understand it, and you don't usually use it too much.
insert image description here

Guess you like

Origin blog.csdn.net/qq_45171957/article/details/124231051